我试图通过将F添加到第四行(如果是正确的话,在python中为数字3)来修改文件夹中的一组文件。在下面的代码中,代码只是连续运行,没有进行修改,有人有想法吗?
import os
from glob import glob
list_of_files = glob('*.gjf') # get list of all .gjf files
for file in list_of_files:
# read file:
with open(file, 'r+') as f:
lines=f.readlines()
for line in lines:
lines.insert(3,'F')
答案 0 :(得分:0)
您无法以这种方式使用Python编辑文件。您将需要创建一个临时文件,然后最后通过重命名该临时文件并删除该临时文件来进行一些清理。核心逻辑是通读原始文件,并将F
添加到第四行,否则只需添加该行即可。可以使用以下功能完成此操作:
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
找到第4行。然后,将使用该行并将\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)
答案 1 :(得分:0)
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)