Answers for "python write line in file"

3

python writeline file

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

python write text file on the next line

file = open("sample.txt", "w")
file.write("Hellon")
file.write("Worldn")
file.close()
Posted by: Guest on November-08-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 "python write line in file"

Python Answers by Framework

Browse Popular Code Answers by Language