Answers for "write a text file line by line python"

1

how to read a text file line by line in python

# Open the file with read only permit
f = open('my_text_file.txt')
# use readline() to read the first line 
line = f.readline()
# use the read line to read further.
# If the file is not empty keep reading one line
# at a time, till the file is empty
while line:
    # in python 2+
    # print line
    # in python 3 print is a builtin function, so
    print(line)
    # use realine() to read next line
    line = f.readline()
f.close()
Posted by: Guest on September-07-2020
0

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()
Posted by: Guest on November-13-2021

Code answers related to "write a text file line by line python"

Python Answers by Framework

Browse Popular Code Answers by Language