Writing Line to a Text file in python
# Open a file for writing and insert some records
>>> f = open('test.txt', 'w')
>>> f.write('applen')
>>> f.write('orangen')
>>> f.write('pearn')
>>> f.close() # Always close the file
# Check the contents of the file created
# Open the file created for reading and read line(s) using readline() and readlines()
>>> f = open('test.txt', 'r')
>>> f.readline() # Read next line into a string
'applen'
>>> f.readlines() # Read all (next) lines into a list of strings
['orangen', 'pearn']
>>> f.readline() # Return an empty string after EOF
''
>>> f.close()
# Open the file for reading and read the entire file via read()
>>> f = open('test.txt', 'r')
>>> f.read() # Read entire file into a string
'applenorangenpearn'
>>> f.close()
# Read line-by-line using readline() in a while-loop
>>> f = open('test.txt')
>>> line = f.readline() # include newline
>>> while line:
line = line.rstrip() # strip trailing spaces and newline
# process the line
print(line)
line = f.readline()
apple
orange
pear
>>> f.close()