问题描述
我需要创建一定数量的文件,这些文件总是在他们里面同样的思路。
使用此脚本,我可以创建“schede”文件夹,其中创建了一定数量的 *.tex 文件。
乳胶串被写入仅在最后一个标签,而其他保持空白。我如何填写所有表格?
import os
import subprocess
work_path = os.path.abspath(os.path.dirname(__file__))
if not os.path.exists("schede"):
os.mkdir("schede")
os.chdir(os.path.expanduser(work_path+"/schede"))
n = 5 #put the number as you wish
for i in range(n):
file_name = "S"+str(i).zfill(1)+".tex"
subprocess.call(['touch',file_name]) #crea 34 file s.tex
def append_new_line(file_name,text_to_append):
"""Append given text as a new line at the end of file"""
# Open the file in append & read mode ('a+')
with open(file_name,"a+") as file_object:
# Move read cursor to the start of file.
file_object.seek(0)
# If file is not empty then append '\n'
data = file_object.read(100)
if len(data) > 0:
file_object.write("\n")
# Append text at the end of file
file_object.write(text_to_append)
def append_multiple_lines(file_name,lines_to_append):
# Open the file in append & read mode ('a+')
with open(file_name,"a+") as file_object:
appendEOL = False
# Move read cursor to the start of file.
file_object.seek(0)
# Check if file is not empty
data = file_object.read(100)
if len(data) > 0:
appendEOL = True
# Iterate over each string in the list
for line in lines_to_append:
# If file is not empty then append '\n' before first line for
# other lines always append '\n' before appending line
if appendEOL == True:
file_object.write("\n")
else:
appendEOL = True
# Append element at the end of file
file_object.write(line)
def main():
append_new_line(file_name,'This is second line')
print('Append multiple lines to a file in Python')
list_of_lines = [
'\ecvtitle{}{}','\ecvitem{\ecvhighlight{Organizzato da:}}{\\textbf{}}','\ecvitem{\ecvhighlight{}}{}','\ecvitem{}{}','\ecvitem{\ecvhighlight{Programma Formativo:}}{}','\smallskip','\ecvitem{}{','\\begin{ecvitemize}'
'\item scrivere un\'item','\\end{ecvitemize}','}']
# Append strings in list as seperate new lines in the end of file
append_multiple_lines(file_name,list_of_lines)
if __name__ == '__main__':
main()
解决方法
正如 @MisterMiyagi 所说的 file_name 是一个变量,所以每次创建文件时它都会被覆盖
我建议创建一个名为 files = [] 的列表
而不仅仅是file_name = "S"+str(i).zfill(1)+".tex"
添加files.append(file_name)
到您创建文件的 for 循环的末尾。
并更改 main 以执行每个文件的说明。
def main():
for file_name in file:
append_new_line(file_name,'This is second line')
print('Append multiple lines to a file in Python')
list_of_lines = [
'\ecvtitle{}{}','\ecvitem{\ecvhighlight{Organizzato da:}}{\\textbf{}}','\ecvitem{\ecvhighlight{}}{}','\ecvitem{}{}','\ecvitem{\ecvhighlight{Programma Formativo:}}{}','\smallskip','\ecvitem{}{','\\begin{ecvitemize}'
'\item scrivere un\'item','\\end{ecvitemize}','}']
# Append strings in list as seperate new lines in the end of file
append_multiple_lines(file_name,list_of_lines)