我有一个最初为python 3.5+编写的脚本。我需要将其转换为2.6.2。
在脚本中,我利用了readlines()
,我相信这两个版本之间的行为有所不同。
具体来说,我正在使用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脚本中,每个readlines()
中都有一个“ 1”,并且根据需要执行了该操作,但是对于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]
...
答案 0 :(得分:0)
要从文件的每一行中读取并分配给变量,我将这种方法用于python 2.6.2
t=open(supportID+"stmp.txt","r")
lines = t.readlines()
t.close()
a=lines[0]
b=lines[1]
c=lines[2]
...
答案 1 :(得分:-2)
尝试以下代码:(我认为它将与python版本> = 2.6一起使用)
with open('lines.txt','r') as f:
lines = f.readlines()
for line in lines:
print(line.strip())