2017-10-09 53 views
-3

编辑我将尝试澄清此问题。我想制作两个csv文件。一个带有文字“问候”,另一个带有文字“问候地球”。问题是我找不到一种方法来让Python用一个写入命令写入多个文件。我正试图找到一种让事情变得更有效率的方法。尝试使用Python对单个命令写入多个文件

此问题被认为是可能的重复。 write multiple files at a time但这个问题有很多部分我不明白。我试图用一个简单的问题来分析这个问题。

hello = open("hello.csv","w") 

world = open("world.csv","w") 

everything = ['hello','world'] 
half = ['world'] 

everything.write("Greetings") 
half.write("Earth") 

hello.close() 
world.close() 
+2

可能的复制[一次写入多个文件](https://stackoverflow.com/questions/13798447/write-multiple-files-at-a-time) – Mel

回答

0

你不完全清楚你为什么试图达到目的。

如果你需要它管理“所有的文件创建需要”你应该通过创建设置(文件名 - >内容)处理这个功能您的文件,然后只写他们。或者,您可以标记文件并根据预设的“标记”生成其内容。

方法1是这样的:

file_dict = {'hello.csv': 'Greetings', 'world.csv': 'Greetings earth'} 
for f in file_dict: 
    with open(f) as working: 
     working.write(file_dict[f]) 

方法2是这样的:

files = {'common': 'hello', 'custom': 'world'} 
common_text = 'Greetings' 
custom_text = ' earth' 
for f in files.keys(): 
    with open(files[f]+'.csv', 'w') as working_file: 
     text = common_text 
     if f is 'custom': 
      text += custom_text 
     working_file.write(text) 

如果你很高兴与您的实现,您可以在“写作”部分迁移到单独的功能(如下所示):

def write_my_stuffs(): 
    for f in file_dict: 
     with open(f) as working: 
      working.write(file_dict[f]) 

file_dict = {'animal.csv': 'I like dogs', 
      'candy.csv': 'I like chocolate cake'} 
write_my_stuffs() 
+0

非常感谢您的帮助。这很有帮助。对于将来阅读此内容的人,我将发布我所达到的解决方案。 – Tom

0

csv“,”w“)

世界=打开( “world.csv”, “W”)

一切= [你好,世界] 一半= [世界]

对一切X: x.write(”问候语 “)

关于x的一半: x.write(” 大地“)

hello.close() world.close()

+0

不知道为什么,但它一直删除hello = open(hello。off the th of code) – Tom

相关问题