Answers for "write line to file python"

12

append a line to a text file python

# Open a file with access mode 'a'
file_object = open('sample.txt', 'a')
 
# Append 'hello' at the end of file
file_object.write('hello')
 
# Close the file
file_object.close()
Posted by: Guest on March-18-2020
3

python writeline file

f = open("test.txt", "w")
f.writelines(["Hello", "World"])
f.close
Posted by: Guest on May-16-2020
3

python writeline file

f = open("test.txt", "w")
f.write("Hello nWorld")
f.close
Posted by: Guest on May-16-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 line to file python"

Python Answers by Framework

Browse Popular Code Answers by Language