簡體   English   中英

在python中的每一行后插入新行

[英]Insert new line after every line in python

python 的絕對新手只是試圖自動化一些過程。 經過一番研究,我了解到 fileinput 可用於在 python 中打開、讀取和寫入文件。 為了解決我的問題,我相信我需要:

  • 打開文件
  • 創建文件的備份
  • 讀取文件
  • 為文件中的行數創建一個 for 循環
  • 執行新行的創建
  • 轉到下一行並重復
  • 保存並關閉文件

我無法從 docs.python 的文檔中找出執行此操作所需的方法/函數,並且在閱讀了其他一些帖子后,坦率地說,我更加困惑,因為他們建議也使用其他模塊。

任何和所有的幫助將不勝感激,謝謝

這是一個示例程序

  1. 備份現有文件,
  2. 讀取現有文件的行,
  3. 將修改后的行保存到一個新文件中,並且
  4. 跟蹤行數。

這個例子是為了展示 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 的目錄中打開命令行並執行它,您應該看到兩個新文件:

  • somefile.txt.bak - somefile.txt 的備份
  • output.txt - somefile.txt 的修改版本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM