06.0 Python‎ > ‎Python Notes‎ > ‎File Processing‎ > ‎

Reading And Writing Text Files

Read one file, write to a different file

Copy a file line by line, OR add some processing before writing the line.
 def copyLineByLine(fname):
    with open(fname, 'r') as f_in, open('Copy.txt', 'w')as f_out: 
             for line in f_in:
            # process the line here, if required
            f_out.write(line)
    print('done')


Read and Write to the same file.


 def writelinesf(fname):
    # reads all lines in a file, 
    # then adds a second copy to the end of the file.
    # 
    f = open(fname, 'r+')
    lines = f.readlines()
    f.writelines(lines)
    f.close()










Comments