How to read and write multiple files?

后端 未结 8 1203
南方客
南方客 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()
    

提交回复
热议问题