-3

EDIT I will try to clarify this question. I want to make two csv files. One with the text "Greetings", the other with the text "Greetings earth". The problem is I can't find a way to ask python to write to multiple files with one write command. I am trying to find a way to make things more efficient.

This question was identified as a possible duplicate of this. write multiple files at a time but there are a lot more parts to that question that I don't understand. I am trying to isolate this problem in as simple a question as I can.

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()
Tom
  • 1
  • 1
  • 2
    Possible duplicate of [write multiple files at a time](https://stackoverflow.com/questions/13798447/write-multiple-files-at-a-time) – Mel Oct 09 '17 at 09:45

2 Answers2

0

It is not entirely clear what any why you try to achieve.

If you need a function which manages 'all your file creation needs' you should probably approach this by creating the setup (file names -> contents) of your files then just write them. Alternatively you can label the files and generate their contents based on the preset 'flags'.

approach 1 is something like this:

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

approach 2 is something like this:

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)

If you are happy with your implementation, you can migrate the 'writing' part to a separate function (something like this):

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()
Trapli
  • 1,517
  • 2
  • 13
  • 19
  • Thank you so much for your help. This is helpful. For people reading this in the future I will post the solution I arrived at. – Tom Oct 12 '17 at 11:44
0

csv","w")

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

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

for x in everything: x.write("Greetings")

for x in half: x.write(" Earth")

hello.close() world.close()

Tom
  • 1
  • 1
  • Not sure why but it keeps deleting hello = open(hello. off the beginning of th code – Tom Oct 12 '17 at 11:49