I have a script originally written for python 3.5+. I am needing to convert it to 2.6.2. In the script I utilize readlines()
which I believe behaves differently between the two versions. Specifically I am using the readlines()
to retrieve data from a txt file that is separated by line breaks.
Here is a snippit:
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))
In my script for 3.x I had a '1' in each of the readlines()
and it performed as needed, however with 2.x this does not work. I have tried entering values 1-7 and blank as seen above.
With some research I discovered that some 2.x users use with open(filename)
Is this the preferred method or is there a way to alter my original to make it work?
EDIT: So im going to use this format
with open(supportID+"stmp.txt") as t:
for line in t:
print(line)
I plugged this in and it works, printing each line as a line in my shell. Now I will want to use this to assign each line to a variable.
EDIT 2: This is currently working for my environment but is not best practice for this function. Reads in each line and assigns each line to a variable.
t=open(supportID+"stmp.txt","r")
lines = t.readlines()
t.close()
a=lines[0]
b=lines[1]
c=lines[2]
...
To read in each line from the file and assign to a variable I used this method for python 2.6.2
t=open(supportID+"stmp.txt","r")
lines = t.readlines()
t.close()
a=lines[0]
b=lines[1]
c=lines[2]
...
try this code: (I assume it will work with python version >= 2.6)
with open('lines.txt','r') as f:
lines = f.readlines()
for line in lines:
print(line.strip())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.