文件名是可变的 - 不写入文件

时间:2016-05-31 19:52:47

标签: python file

我有一个关于某些人口(列和行)的大文件。我想阅读文件并提取一些信息并编写一个脚本来为每个人口创建一个文件。

现在我想写每个填充文件“变量名”的问题 只需将大文件的最后一行写入正确的填充。 其他文件为空。当我尝试打印到终端时,它会正确打印数据。

*文件已在代码的前一部分中创建。

有什么建议吗?

for item in d: # d is a set to hold the populations names
    filename= item # hold the file name
    if item == 'population': # exclude the header of the column
        continue
    elif item== pop:
        with open(filename+'.txt', 'a') as f: # add to the specific population file
            f.write(str(fID) +" "+ sID)  # write the two columns to the file

1 个答案:

答案 0 :(得分:0)

只有存储在'item'中的名称与存储在'pop'中的名称相同时,您的代码才会写入文件。可能你想生成几个文件,所以代码可能应该是:

if item == 'population': # exclude the header of the column
    continue
else:
    with ...
相关问题