File operations‎ > ‎

Files: read & write

Read

read file line-wise
with open('example.txt') as f:
    for line in f:
        l=line.strip()
        print(l)

or, shorter
for line in (l.strip() for l in open('example.txt')):
    print(line)

remove/ignore comment lines in example.txt (marked by '#')
for line in (l.strip() for l in open('example.txt') if not l.startswith('#')):
    print(line)

remove/ignore comment and empty lines in example.txt
for line in (l.strip() for l in open('example.txt') if not l.startswith('#') and l.strip()):
    print(line)

memory efficient line by line iteration (for one time use)
for line in (l.strip() for l in open('example.txt')):
    print(line)
converting file into a list of lines (for repeated loops over lines)
for line in [l.strip() for l in open('example.txt')]:
    print(line)

read entire file

filecontent = f.read()

read entire file and close immediately after block ends
with open('example.txt', 'r') as f:
    filecontent = f.read()


catch headerline separately
with open('example.txt') as f:
    headerline=f.readline().strip()
    for line in f:
        l=line.strip()
        print(l)


skip header line
with open('example.txt') as f:
    next(f)
    for line in f:
        l=line.strip()
        print(l)

# skip the top 5 header lines
with open('example.txt') as f:
    for i in range(5):
        next(f)
    for line in f:
        l=line.strip()
        print(l)



Write


write to file, writing 'Hello world' and newline (\n) to the file 'example.txt', file is closed automatically after 'with' block ends
with open('logfile.txt', 'w') as f:
     f.write('Hello world\n')

append to file (add text to end of file), file is closed automatically after 'with' block ends
with open('logfile.txt', 'a') as f:
     f.write('adding text to end of file')

open()-write()-close() - classic way
f = open('example.txt', 'w')
f.write('Hello world\n')
f.close() # close a file to give free any taken system resources


'r'   read only (default)
'w'   write only (deletes existing file with the same)
'r+' read and write
'a'   open and adding (append) text to the end of an existing file


Newline \n or \r\n ?
Always use '\n' for text files, also under Windows, '\n' will be automatically converted into '\r\n' in Windows (when file opened in normal text mode 'w', not as binary 'wb'). Platform specific string is defined in os.linesep