[英]Insert new line after every line in python
python 的絕對新手只是試圖自動化一些過程。 經過一番研究,我了解到 fileinput 可用於在 python 中打開、讀取和寫入文件。 為了解決我的問題,我相信我需要:
我無法從 docs.python 的文檔中找出執行此操作所需的方法/函數,並且在閱讀了其他一些帖子后,坦率地說,我更加困惑,因為他們建議也使用其他模塊。
任何和所有的幫助將不勝感激,謝謝
這是一個示例程序
這個例子是為了展示 Python 的一些核心特性。 例如,它展示了如何使用循環、如何打開文件以及如何在 Python 中使用字符串。
假設您有一個名為somefile.txt的文件:
This is a file. Hi to you!
假設您在同一目錄中有一個名為example.py的文件,其中包含以下幾行:
import shutil # file copy
import os # new line separator
# the full path of the file
path = "somefile.txt"
# path to where to back it up
backup_path = "somefile.txt.bak"
# path to save output file
output_path = "output.txt"
# create backup first
shutil.copyfile(path, backup_path)
lineNumber = 0
# open the file for reading
with open(path) as input:
# open output for writing
with open(output_path, "w") as output:
# keep reading lines
while True:
# read a line from input
line = input.readline()
# end of file?
if line == "":
# break out of `while` loop
break
lineNumber += 1
# do something with the line
line = str(lineNumber) + ": " + line
# save to output
output.writelines(line)
# files are automatically closed for you
如果在包含 example.py 的目錄中打開命令行並執行它,您應該看到兩個新文件:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.