How to read and write multiple files?

后端 未结 8 1042
南方客
南方客 2020-12-24 00:52

I want to write a program for this: In a folder I have n number of files; first read one file and perform some operation then store result in a separate file. Then

相关标签:
8条回答
  • 2020-12-24 01:22

    I think what you miss is how to retrieve all the files in that directory. To do so, use the glob module. Here is an example which will duplicate all the files with extension *.txt to files with extension *.out

    import glob
    
    list_of_files = glob.glob('./*.txt')           # create the list of file
    for file_name in list_of_files:
      FI = open(file_name, 'r')
      FO = open(file_name.replace('txt', 'out'), 'w') 
      for line in FI:
        FO.write(line)
    
      FI.close()
      FO.close()
    
    0 讨论(0)
  • 2020-12-24 01:24

    This thing also works for reading multiple files, my file name is fedaralist_1.txt and federalist_2.txt and like this, I have 84 files till fedaralist_84.txt

    And I'm reading the files as f.

    for file in filename:
            with open(f'federalist_{file}.txt','r') as f:
                 f.read()
    
    0 讨论(0)
提交回复
热议问题