Writing and reading a new file by passing the files as an argument to a function in a python script
Question: I have a python script that gets input file names from the command prompt. I
created a list to store all the input files and pass that to a function to
create a new file with all the input files merged at once. Now, I pass this
newly written file as an input to another function. I am getting an error
message

**TypeError: coercing to Unicode: need string or buffer, list found**

Code:

    
    
    file_list = []                                                                                                                                                                                                                                                                                                                        
    for arg in range(1,len(sys.argv)-2):    
        file_list.append(sys.argv[arg])
        process_name = sys.argv[len(sys.argv)-1]
    integrate_files(file_list,process_name)
    
    def integrate_files(file_list,process_name):
        with open('result.log', 'w' ) as result:        
           for file_ in file_list:
              for line in open( file_, 'r' ):
                 result.write( line )
        start_process(result,process_name)
    
    def start_process(result,process_name):
        with open(result,'r') as mainFile:
           content = mainFile.readlines()
    

I am getting this error highlighted at the lines having the word
**with.open()**. I tried to print the abspath of the result.log file. It
printed **closed file 'result.log', mode 'w' at 0x000000000227578**. Where am
I going wrong ? How should I create a new file and pass it to a function?


Answer: Your problem is that `result` is a closed file object:

    
    
    start_process(result,process_name)
    

I think you want

    
    
    start_process('result.log', process_name)
    

You could clean the script up a bit with

    
    
    import shutil
                                                                                                file_list = sys.argv[1:-1]
    process_name = sys.argv[-1]
    integrate_files(file_list,process_name)
    
    def integrate_files(file_list,process_name):
        with open('result.log', 'w' ) as result:        
           for file_ in file_list:
               with open(file_) as infile:
                   shutil.copyfileobj(infile, result)
        start_process('result.log',process_name)
    
    def start_process(result,process_name):
        with open(result,'r') as mainFile:
           content = mainFile.readlines()
    

