I have a template txt file. This template needs to be written as 10 new files where I can then make amendments to each file based on certain conditions (not relevant to the question).
I read my template file as follows:
with open('template.txt', 'r') as template_file:
file_lines = template_file.readlines()
file_lines = [line.rstrip('\n') for line in file_lines]
for i in range(10):
new_file = open('output_%s' % i, 'w')
new_file.write(file_lines)
new_file.close()
It won't work as I cannot write a list to each file, it must be a string, but I don't know how to get every element from that list to be written in the same file 10 times...Each time I try it a different way I end up getting each line on different files, rather than all lines in all files.
Something wrong in my logic I cannot work out.
Another way I can do it as :
template_file = open('template.txt', 'r')
template_lines = template_file.read()
for i in range(10):
new_files = open('output_%s' % i, 'w')
new_files.write(template_lines)
But I want to be able amendment particular lines which makes it more convenient to write into each new file line by line (via readlines())
You can use the python method writelines(<iterable>)
on the fileobject.
Something like:
with open('template.txt', 'r') as template_file:
file_lines = template_file.readlines()
file_lines = [line.rstrip('\n') for line in file_lines]
for i in range(10):
with open('output_%s' % i, 'w') as new_file:
new_file.write_lines(file_lines)
Also not sure you need the rstrip('\\n')
as readlines()
already should be removing newlines.
尝试缩进new_file.close()
以便在每个for循环之后将其保存
I don't fully understand what you want to achieve. Anyways, here is a code snippet of how you can write the same line to every one of the 10 files:
with open('template.txt', 'r') as template_file:
file_lines = template_file.readlines()
file_lines = [line.rstrip('\n') for line in file_lines]
for line in file_lines:
for i in range(10):
new_file = open('output_%s' % i, 'a') # appending content
new_file.write(line)
new_file.close()
or even this, if you prefer:
with open('template.txt', 'r') as template_file:
file_lines = template_file.readlines()
file_lines = [line.rstrip('\n') for line in file_lines]
for i in range(10):
new_file = open('output_%s' % i, 'w')
for line in file_lines:
new_file.write(line)
new_file.close()
The writelines
method did the job.
with open(TRANSFER_SKED, 'r') as template_file:
file_lines = template_file.readlines()
# file_lines = [i.rstrip('\n') for i in file_lines]
for i in range(10):
with open('output_%s.txt' % i, 'w') as new_file:
new_file.writelines(file_lines)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.