def readFromFile (fileName):
sourceFile = open (fileName, 'r')
text = []
for address in sourceFile.readlines ():
if '\n' in address: text.append (address [:-1])
else: text.append (address)
return text
sourceFile.close ()
def writeToFile (text):
resultFile = open ('result.txt', 'w')
for data in text:
resultFile.write (data + '\n')
resultFile.close ()
addresses = read ('mysource.txt')
for address in addresses:
text = read (address)
write (text)
1 回答
由于评论中的文件名太大而无法编写,我只是举了一个小例子 .
假设您有一个源文件(
mysource.txt
),其中包含其他文件的地址 .每个地址都是一个文本文件,其数据如下:
您希望将所有数据存储到
result.txt
文件中 .看看我的示例代码 .
readFromFile ()
函数接受单个文件地址,并在单个列表中输出文件中的所有行,即addresses
.现在,对于每个地址,for循环实现相同的
readFromFile ()
函数来遍历内部文件数据,并在result.txt
中写入(使用writeToFile ()
函数) .