2 回答
TA贡献1799条经验 获得超8个赞
for file in files:
# read your file's lines
with open(file, 'r') as f:
lines = f.readlines()
# add the value to insert in the list of lines at index 3
# don't forget line-break (\n)
lines.insert(3, 'F\n')
# join lines to create a string
text = ''.join(lines)
# don't forget to write the string back in your file
with open(file, 'w') as f:
f.write(text)
TA贡献1820条经验 获得超2个赞
您无法以这种方式使用 Python 编辑文件。您需要创建一个临时文件,然后通过重命名临时文件并删除临时文件在最后进行一些清理。核心逻辑是通读原始文件并F在第4行添加一个,否则只需添加该行。这可以通过这样的函数来完成:
import os
def add_f_4th_line(filename):
with open(filename, 'r') as f_in:
with opne('temp', 'w') as f_out:
for line_number, line_contents in enumerate(f_in):
if line_number == 3:
f_out.write(line_contents.replace('\n', 'F\n'))
else:
f_out.write(line_contents)
os.rename('temp', filename)
os.remove('temp')
enumerate将继续生成行号和行内容的迭代器,因此只需迭代每一行,您就可以找到带有line_number == 3. 然后,它将采用该行并替换\n为F\n. \n是一个换行符,所以我假设行尾就是这个字符。因此,在添加此函数后,您只需为通过调用获得的每个文件调用此函数glob。
import os
from glob import glob
list_of_files = glob('*.gjf') # get list of all .gjf files
for file in list_of_files:
add_f_4th_line(file)
添加回答
举报