繁体   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