how to read a list of txt files in a folder in python

前端 未结 4 1760
攒了一身酷
攒了一身酷 2020-12-13 21:50

I am new to python, I wrote an algorithm to read 10 txt files in a folder and then write the first line of each of them in one txt outfile. but it doesn\'t work. I mean afte

4条回答
  •  半阙折子戏
    2020-12-13 22:17

    Lets assume you have files in the folder path path = /home/username/foldername/

    so you have all the files in the path folder, to read all the files in the folder you should use os or `glob' to do that.

    import os
    path = "/home/username/foldername/"
    savepath = "/home/username/newfolder/" 
    for dir,subdir,files in os.walk(path):
        infile = open(path+files)
        outfile = open(savepath,'w')
        a = infile.readline().split('.')
        for k in range (0,len(a)):
            print(a[0], file=outfile, end='')
    infile.close()
    outfile.close
    print "done"
    

    or using glob you can do it much lesser lines of code.

    import glob
    path = "/home/username/foldername/"
    savepath = "/home/username/newfolder/"
    for files in glob.glob(path +"*.txt"):
        infile = open(files)
        outfile = open(savepath,'w')
        a = infile.readline().split('.')
        for k in range (0,len(a)):
            print(a[0], file=outfile, end='')
    infile.close()
    outfile.close
    print "done" 
    

    hope it might work for you.

提交回复
热议问题