[英]python how to delete a line from a txt file and add data
我的程序從文件夾中讀取所有 txt 文件並轉換 txt 文件中的數字。 例如,我的 txt 文件之一是這個
1 0.487500 0.751667 0.112500 0.246667
0 0.464375 0.648333 0.046250 0.083333
4 0.500000 0.352500 0.055000 0.098333
它們都具有與上面相同的框架,但行可能更少或更多。 到目前為止,我已經能夠使用下面的代碼轉換它們
import os
for root, dirs, files in os.walk('./'):
for idx, file in enumerate(files):
fname, ext = os.path.splitext(file)
if ext in ['.txt']:
with open((file),'r') as f:
lines = f.readlines()
for line in lines:
item = line.split(" ")
item[1] = float(item[1])
item[1] = ((item[1]) * 800 - 256) / 288
item[1] = '{:.6f}'.format(round(item[1],6))
item[1] = str(item[1])
item[2] = float(item[2])
item[2] = ((item[2]) * 600 - 88) / 512
item[2] = '{:.6f}'.format(round(item[2],6))
item[2] = str(item[2])
item[3] = float(item[3])
item[3] = ((item[3]) * 800) / 288
item[3] = '{:.6f}'.format(round(item[3],6))
item[3] = str(item[3])
item[4] = float(item[4])
item[4] = ((item[4]) * 600) / 512
item[4] = '{:.6f}'.format(round(item[4],6))
item[4] = str(item[4])
item = ' '.join(item)
print (item)
並使用上面的代碼和txt文件的結果是
1 0.465278 0.708985 0.312500 0.289063
0 0.401042 0.587890 0.128472 0.097656
4 0.500000 0.241211 0.152778 0.115234
效果很好,但我需要將結果替換為原始結果。 我怎么能做到呢?
重要提示:最好將您的結果寫入新文件,以便在發生故障時原始文件不會被破壞。
無論哪種方式,這是執行您指定的代碼:
#!/usr/bin/env python3
import os
def main():
for _, _, files in os.walk('./'):
for _, file in enumerate(files):
_, ext = os.path.splitext(file)
if ext in ['.txt']:
processed_lines = list()
with open(file, 'r') as f:
for line in f.readlines():
item = line.split(" ")
item[1] = float(item[1])
item[1] = ((item[1]) * 800 - 256) / 288
item[1] = '{:.6f}'.format(round(item[1], 6))
item[1] = str(item[1])
item[2] = float(item[2])
item[2] = ((item[2]) * 600 - 88) / 512
item[2] = '{:.6f}'.format(round(item[2], 6))
item[2] = str(item[2])
item[3] = float(item[3])
item[3] = ((item[3]) * 800) / 288
item[3] = '{:.6f}'.format(round(item[3], 6))
item[3] = str(item[3])
item[4] = float(item[4])
item[4] = ((item[4]) * 600) / 512
item[4] = '{:.6f}'.format(round(item[4], 6))
item[4] = str(item[4])
processed_lines.append(' '.join(item))
with open(file, 'w') as f:
f.write('\n'.join(processed_lines))
if __name__ == '__main__':
main()
首先,我添加了f.write()
調用以將數據寫回磁盤。
除此之外,我還做了一些改進:
main()
中,因為這是最佳實踐_
替換所有未使用的變量雖然前面的代碼對於初學者來說很容易理解,但它的缺點是它打開了兩次文件。
可以保持文件打開並使用相同的文件對象進行讀寫,以提高性能:
#!/usr/bin/env python3
import os
def main():
for _, _, files in os.walk('./'):
for _, file in enumerate(files):
_, ext = os.path.splitext(file)
if ext in ['.txt']:
processed_lines = list()
# Open with 'r+', indicating that we want to both read
# and write the file
with open(file, 'r+') as f:
for line in f.readlines():
item = line.split(" ")
item[1] = float(item[1])
item[1] = ((item[1]) * 800 - 256) / 288
item[1] = '{:.6f}'.format(round(item[1], 6))
item[1] = str(item[1])
item[2] = float(item[2])
item[2] = ((item[2]) * 600 - 88) / 512
item[2] = '{:.6f}'.format(round(item[2], 6))
item[2] = str(item[2])
item[3] = float(item[3])
item[3] = ((item[3]) * 800) / 288
item[3] = '{:.6f}'.format(round(item[3], 6))
item[3] = str(item[3])
item[4] = float(item[4])
item[4] = ((item[4]) * 600) / 512
item[4] = '{:.6f}'.format(round(item[4], 6))
item[4] = str(item[4])
processed_lines.append(' '.join(item))
# Move the current position back to the beginning of the file
f.seek(0)
# Delete everything in the file
f.truncate()
# Write new content
f.write('\n'.join(processed_lines))
if __name__ == '__main__':
main()
此外,這里有一個關於如何以更緊湊的方式編寫函數的建議:
#!/usr/bin/env python3
import os
def main():
for _, _, files in os.walk('./'):
for _, file in enumerate(files):
_, ext = os.path.splitext(file)
if ext in ['.txt']:
processed_lines = list()
# Open with 'r+', indicating we want both read and write the file
with open(file, 'r+') as f:
for line in f.readlines():
item = line.split(" ")
numbers = list(map(float, item[1:5]))
numbers[0] = (numbers[0] * 800 - 256) / 288
numbers[1] = (numbers[1] * 600 - 88) / 512
numbers[2] = (numbers[2] * 800) / 288
numbers[3] = (numbers[3] * 600) / 512
item[1:5] = map(lambda el: '{:.6f}'.format(round(el, 6)), numbers)
processed_lines.append(' '.join(item))
# Move the current position back to the beginning of the file
f.seek(0)
# Delete everything in the file
f.truncate()
# Write new content
f.write('\n'.join(processed_lines))
if __name__ == '__main__':
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.