Python 一次写入多个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13798447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:38:57  来源:igfitidea点击:

write multiple files at a time

pythonfile

提问by shreya

I have a file with 196 list in it,and I want to create new 196 output files and write each of the list in a new file, so that I will have 196 output files each containing 1 list of input data Here is the input file:

我有一个包含 196 个列表的文件,我想创建新的 196 个输出文件并将每个列表写入一个新文件,这样我将有 196 个输出文件,每个文件包含 1 个输入数据列表这是输入文件:

"['128,129', '116,118', '108,104', '137,141', '157,144', '134,148', '138,114', '131,138', '248,207', '208,247', '246,248', '101,106', '131,115', '119,120', '131,126', '138,137', '132,129']"
"['154,135', '151,147', '236,244', '243,238', '127,127', '125,126', '122,124', '123,126', '127,129', '122,121', '147,134', '126,132', '128,137', '233,222', '222,236', '125,126']"

.....here for eg, I have given only 2 list but total 196 list are present. Output should be:

.....在这里,例如,我只给出了 2 个列表,但总共有 196 个列表。输出应该是:

file 1 :

文件 1:

128,129
116,118
108,104

file2 :

文件2:

154,135
151,147
236.244

Current code:

当前代码:

fn = open("/home/vidula/Desktop/project/ori_tri/inpt.data","r")
fnew = fn.read()
fs = fnew.split('\n')
for value in fs:
    f = [open("/home/vidula/Desktop/project/ori_tri/input_%i.data" %i,'w') for i in range(len(list_of_files))]
    f.write(value)
    f.close()

Error: list do not attribute write.

错误:列表不写属性。

回答by pranshus

I am assuming that you want to read 196 files and then write the data (after some modification) to new 196 files. If you use maps and reduce (functional programming) it can do what you want. Though without much explanation in the question, I am unable to help much.

我假设您要读取 196 个文件,然后将数据(经过一些修改)写入新的 196 个文件。如果您使用 map 和 reduce(函数式编程),它可以做您想做的事。虽然在问题中没有太多解释,但我无能为力。

def modify(someString):
    pass # do processing

def newfiles(oldfilename): return '%s.new.txt'%(oldfilename) # or something 

filenames = ('a', 'b', 'c', 'd', ....) 
handles = [(open(x, 'r'), open(newfile(x), 'w')) for x in filenames] # not using generator
tmp = [y[1].write(modify(y[0].read())) for y in handles) 

回答by Samuele Mattiuzzo

your f is a list of files, you have to loop through it:

你的 f 是一个文件列表,你必须遍历它:

for file in f:
   file.write(value)

回答by John Zwinck

Your current code is loading everything into memory, which is quite unnecessary, then it is making a list in a place that is not appropriate, hence your error. Try this:

您当前的代码正在将所有内容加载到内存中,这是非常不必要的,然后它在不合适的地方制作了一个列表,因此您的错误。尝试这个:

fn = open("/home/vidula/Desktop/project/ori_tri/inpt.data","r")
for i, line in enumerate(fn):
    f = open("/home/vidula/Desktop/project/ori_tri/input_%i.data" %i,'w')
    f.write(line)
    f.close()

This will just write each line as it was to each file. Look up the enumeratefunction I used to do the indexing.

这只会将每一行写入每个文件。查找我用来做索引的enumerate函数。

Having done this, you will still need to write parsing logic to turn each line into a series of lines...I'm not going to do that for you here, since your original code didn't really have logic for it either.

完成此操作后,您仍然需要编写解析逻辑以将每一行转换为一系列行……我不会在这里为您这样做,因为您的原始代码也没有真正的逻辑。

回答by John Zwinck

I think this is what you are looking for:

我认为这就是你要找的:

with open("/home/vidula/Desktop/project/ori_tri/inpt.data","r") as fn:
    listLines = fn.readlines()

for fileNumber, line in enumerate(listLines):
    with open("/home/vidula/Desktop/project/ori_tri/input{0}.data".format(fileNumber), "w") as fileOutput:
        fileOutput.write(line)

回答by Rider

You can't make python look inside the list class for the write object as an iterable in the list comprehension. The list is not compatible with the write() method. In python lists are appended.

你不能让 python 在列表类中查找 write 对象作为列表理解中的可迭代对象。该列表与 write() 方法不兼容。在 python 列表中附加。

Assuming your data file has new lines already in the file, create a filter object to remove blank lines then iterate:

假设您的数据文件中已有新行,请创建一个过滤器对象以删除空行,然后进行迭代:

string1 = '128,129', '134, 167', '127,189'
string2 = '154, 134', '156, 124', '138, 196'
l1 = list(string1)
l2 = list(string2)
data = [l1, l2]
f = open("inpt.data", "w")
for val in data:
    f.write(str(val))
    f.write('\n')
f.close()

with open("inpt.data", "r", encoding='utf-8') as fs:
    reader = fs.read()
    file = reader.split('\n')
    file = filter(None, file)

The simplest way:

最简单的方法:

# create one file for each list of data (1) on every new line 
i = 0
for value in file:
    i += 1
    f = open("input_%s.data" % i, 'w')
    f.write(value)
fs.close()

The pythonic simple way:

pythonic简单的方法:

for i, line in enumerate(file):
    fi = open("input_%s.data" % i, 'w')
    fi.write(line)
fs.close()