0

I want to add two or more files in just one file with all info. My code is:

def add_file(filenames, output_file):
    with open(output_file, 'w') as master_file:
        master_file.write('C/A,UNIT,SCP,DATEn,TIMEn,DESCn,ENTRIESn,EXITSn\n')
        for filename in filenames:
            with open(filename, 'r') as infile:
                master_file.write(infile.read())

When I call to put all files like this:

add_file('turnstile_170603.txt','out.txt')

Show:

IOError: [Errno 2] No such file or directory: 't'

Why? What I did wrong?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Luiz
  • 67
  • 1
  • 1
  • 7
  • 2
    You're passing in a string for `filenames`, so it's iterating through the string – Wondercricket Aug 10 '17 at 19:00
  • When `filenames` is a string instead of a list, it iterates through the individual letters of the string, not what you want. If your string does contain a (whitespace-separated) list, first use the `.split` command to generate the list. – smci Sep 12 '18 at 07:10

3 Answers3

2

You passed a string as filenames and the function iterated it by characters. Pass a list instead. It might be better to rename the function from add_file to add_files.

Be careful with out.txt; you should open it in append mode instead of 'w' mode if you want to call this function more than 1 time.

wim
  • 338,267
  • 99
  • 616
  • 750
0

You are passing a string for filenames, so the function is iterating it through the string. Pass a list to fix this.

liam
  • 1,918
  • 3
  • 22
  • 28
0
for filename in filenames:

the above line is iterating one at time through your first argument, which happens to be a string.

When you call this line

with open(filename, 'r') as infile:

'filename' is what exists as an item in filenames. The error happens as soon as it reaches the first letter of the string.

blake
  • 76
  • 1
  • 4