[英]Write output of for loop to multiple files
我試圖讀取txt
文件的每一行,並打印出不同文件中的每一行。 假設,我有一個文本如下:
How are you? I am good.
Wow, that's great.
This is a text file.
......
現在,我希望filename1.txt
具有以下內容:
How are you? I am good.
filename2.txt
有:
Wow, that's great.
等等。
我的代碼是:
#! /usr/bin/Python
for i in range(1,4): // this range should increase with number of lines
with open('testdata.txt', 'r') as input:
with open('filename%i.txt' %i, 'w') as output:
for line in input:
output.write(line)
我得到的是,所有文件都包含文件的所有行。 我希望每個文件只有1行,如上所述。
在for循環中移動第二個with
語句,而不是使用外部for循環來計算行數,使用enumerate
函數返回一個值及其索引:
with open('testdata.txt', 'r') as input:
for index, line in enumerate(input):
with open('filename{}.txt'.format(index), 'w') as output:
output.write(line)
此外, format
的使用通常優先於%
字符串格式化語法。
對於如何從線路閱讀器獲取計數器,這是一個很好的答案。 通常,您需要一個循環來創建文件和讀取每一行而不是外部循環創建文件和內部循環讀取行。
解決方法如下
#! /usr/bin/Python
with open('testdata.txt', 'r') as input:
for (counter,line) in enumerate(input):
with open('filename{0}.txt'.format(counter), 'w') as output:
output.write(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.