Reputation: 2977
I'm reading and appending to a text file that is being opened and read every time my Python program runs. It's basically a log of strings.
The problem is that when I initially write to the blank file, I have to include action.write('\n')
in order for the next string to be printed on the next line.
But then, when I read through the file the next time my Python program runs, it reads the "\n" and it gets concatenated to the previous element, which is added to a list.
Here's what is basically happening:
pc = ["121", "343", "565", "787"]
with open(r"C:\tt.txt", "r+") as act:
curr=[]
for row in act:
if row == '\n':
pass
else:
curr.append(row)
for i in pc:
act.write(i)
act.write("\n")
print curr
>> curr = ['121\n', '343\n', '565\n', '787\n', '121\n', '343\n', '565\n', '787\n', '121\n', '343\n', '565\n', '787\n', '121\n', '343\n', '565\n', '787\n', '121\n', '343\n', '565\n', '787\n']
I'm really stumped as to how to get around this.
Upvotes: 0
Views: 3690
Reputation: 18358
Just remove the last character from each row
for row in act:
row = row[:-1]
if row:
curr.append(row)
Upvotes: 1
Reputation: 129011
Strip the lines:
for row in act:
row = row.strip()
if row:
curr.append(row)
Upvotes: 6