将特定行添加到文本文件
Add specific lines to text file
我有一个很长的文本文件,我想执行以下操作...
这是我的文本文件的一部分:
这就是我希望在 运行 代码之后的样子:
任何人都可以在 python 中为此建议任何代码吗?
要了解执行此类操作的基本方法,请查看 Python 中有关读写文件的文档:https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
此外,了解列表理解:https://www.w3schools.com/python/python_lists_comprehension.asp
使用它,您可以采用以下一种易于理解的方法。
打开文件后,读取所有非空行(line.strip()
returns 删除任何前导或尾随空白的字符串 space,并空字符串 returns false).
# add every stripped line in the file if it's not empty
lines = [line.strip() for line in file if line.strip()]
创建一个新列表并用新内容复制数据。
newlines = []
# go from start to end of list, increment by 2
for i in range(0, len(lines), 2):
# add the first part
newlines.append("signed char...")
# add the two parts from the original file
newlines.extend(lines[i:i+2])
# add the last part
newlines.append("};")
将newlines
写入文件。
我有一个很长的文本文件,我想执行以下操作... 这是我的文本文件的一部分:
这就是我希望在 运行 代码之后的样子:
任何人都可以在 python 中为此建议任何代码吗?
要了解执行此类操作的基本方法,请查看 Python 中有关读写文件的文档:https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
此外,了解列表理解:https://www.w3schools.com/python/python_lists_comprehension.asp
使用它,您可以采用以下一种易于理解的方法。
打开文件后,读取所有非空行(
line.strip()
returns 删除任何前导或尾随空白的字符串 space,并空字符串 returns false).# add every stripped line in the file if it's not empty lines = [line.strip() for line in file if line.strip()]
创建一个新列表并用新内容复制数据。
newlines = [] # go from start to end of list, increment by 2 for i in range(0, len(lines), 2): # add the first part newlines.append("signed char...") # add the two parts from the original file newlines.extend(lines[i:i+2]) # add the last part newlines.append("};")
将
newlines
写入文件。