[英]How do I append to a file without adding '\n'?
我正在讀取並附加到一個文本文件,該文件在我的Python程序每次運行時都已打開並讀取。 它基本上是字符串的對數。 問題是,當我最初寫入空白文件時,必須包含action.write('\\n')
才能在下一行打印下一個字符串。
但是,當我下次運行Python程序時通讀文件時,它會讀取“ \\ n”,並將其串聯到上一個元素中,該元素會添加到列表中。
基本上是這樣的情況:
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']
我真的很困惑如何解決這個問題。
刪除線:
for row in act:
row = row.strip()
if row:
curr.append(row)
只需刪除每一行的最后一個字符
for row in act:
row = row[:-1]
if row:
curr.append(row)
您可以使用
for line in open(somefile):
line = line.strip()
用於刪除尾行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.