我正在閱讀這樣的檔案:
path = '/home/onur/Deep3dPortrait/examples/'
detections = os.listdir(path 'detections/')
landmarks = os.listdir(path 'landmarks/')
for file in detections:
with open(path 'detections/' file, 'r') as f:
print(f.read())
這是輸出:
128.0 96.0
191.0 96.0
182.0 136.0
138.0 181.0
186.0 180.0
如何在每個此類檔案中用空格替換換行符?我希望檔案看起來像這樣:
128.0 96.0 191.0 96.0 182.0 136.0 138.0 181.0 186.0 180.0
我知道我可以使用str.replace('\n', ' '),但我怎樣才能真正逐行編輯檔案的內容?
uj5u.com熱心網友回復:
您仍然可以使用replace,但您需要f.write:
# Open and over-write (r )
with open("file.txt", 'r ') as f:
x = f.read()
x = x.replace("\n", " ")
f.seek(0)
f.write(x)
uj5u.com熱心網友回復:
通常您不會就地編輯檔案:您在其他地方讀取并寫入。成功后,您可以將輸入檔案替換為輸出檔案。
with open('input.txt', 'rt') as fi, open('output.txt', 'wt') as fo:
for line in fi:
fo.write(line.replace('\n', ' '))
# optionally move output.txt to input.txt afterward
話雖如此,對于小檔案和玩具示例,您可以閱讀整個內容,然后以相同的名稱將其寫回:
with open('input.txt', 'rt') as f:
data = f.read()
with open('input.txt', 'wt') as f:
f.write(data.replace('\n', ' '))
uj5u.com熱心網友回復:
您可以考慮使用正則運算式:
import re
path = '/home/onur/Deep3dPortrait/examples/'
detections = os.listdir(path 'detections/')
landmarks = os.listdir(path 'landmarks/')
for file in detections:
with open(path 'detections/' file, 'w') as f:
f.write(re.sub("\n", " ", f.read()))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452187.html
上一篇:str.encode(encoding='utf-8',errors='strict')是否有可能引發UnicodeError?
下一篇:JS鬧鐘需要調整
