0
我有這樣的代碼:爲什麼我的代碼不正確地打印到文本文件?
with open("pool2.txt", "r") as f:
content = f.readlines()
for line in content:
line = line.strip().split(' ')
try:
line[0] = float(line[0])+24
line[0] = "%.5f" % line[0]
line = ' ' + ' '.join(line)
except:
pass
with open("pool3.txt", "w") as f:
f.writelines(content)
應該採取看起來像這樣的臺詞:
-0.597976 -6.85293 8.10038
到具有24加入到第一號的線。像這樣:
23.402024 -6.85293 8.10038
當我使用print
代碼打印行,該行是正確的,但是當它打印文本文件,它打印的原件。
原始文本文件可以找到here。
如何使這些更改影響'內容'? –
@ZachGates請參閱編輯。 – Christian
嚴格地說,它不是一個副本,直到你使用'='。它以兩個對同一個字符串的引用開始,但是賦值改變了'line'引用而不改變'content'引用。你的修復是完美的。 –