社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python readlines()3.x到2.x

Newb 4 You BB • 5 年前 • 1554 次点击  

我有一个最初为python 3.5+编写的脚本。我需要把它转换成2.6.2。 在我使用的脚本中 readlines() 我相信这两个版本的表现是不同的。 特别是我用的 读入() 从用换行符分隔的TXT文件中检索数据。

这是一个笑话:

t=open(supportID+"stmp.txt","r")
timeIn=(t.readlines())
a=(str(timeIn))
supportID=(t.readlines())
b=(str(supportID))
branch=(t.readlines())
c=(str(branch))
clientID=(t.readlines())
d=(str(clientID))
problem=(t.readlines())
e=(str(problem))
solution=(t.readlines())
f=(str(solution))
timeOut=(t.readlines())
g=(str(timeOut))

在我的3.x脚本中,每个 读入() 它可以根据需要执行,但是使用2.x这不起作用。我试着输入1-7的值,如上图所示为空白。

通过一些研究,我发现一些2.x用户使用 with open(filename) 这是首选的方法,还是有办法改变我的原件,使其工作?

编辑: 所以我要用这个格式

with open(supportID+"stmp.txt") as t:
    for line in t:
        print(line)

我插上这个,它就工作了,把每一行打印成一行。现在我想用这个把每一行赋给一个变量。

编辑2: 这目前对我的环境有效,但不是此功能的最佳实践。读取每一行并将每一行赋给一个变量。

t=open(supportID+"stmp.txt","r")
lines = t.readlines()
t.close()
a=lines[0]
b=lines[1]
c=lines[2]
...
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/44266
 
1554 次点击  
文章 [ 2 ]  |  最新文章 5 年前
balderman
Reply   •   1 楼
balderman    6 年前

请尝试以下代码:(我认为它将与python版本一起工作>=2.6)

with open('lines.txt','r') as f:
    lines = f.readlines()
    for line in lines:
       print(line.strip())
Newb 4 You BB
Reply   •   2 楼
Newb 4 You BB    6 年前

读取文件中的每一行并分配给变量 我在Python2.6.2中使用了这个方法

t=open(supportID+"stmp.txt","r")
lines = t.readlines()
t.close()
a=lines[0]
b=lines[1]
c=lines[2]
...