Several ways for python to write files _ 3 ways to read and write text files in python

the first method:

file1 = open("test.txt")

file2 = open("output.txt","w")

while True:

line = file1.readline()

# Logical processing can be done here

file2.write('"'+line[:s]+'"'+",")

if not line:

break

#Remember that it is a good habit to close the file after processing

file1.close()

file2.close()

There are three ways to read a file: read() reads all lines of a text file into a string.

readline() is a line-by-line read

readlines() is to read all the lines in the text file into a list, each line of the text file is an element of the list.

Advantage: readline() can skip specific lines during line reading.

The second method:

File iterator, using for loop method

file2 = open("output.txt","w")

for line in open("test.txt"):

# Logical processing can be done here

file2.write('"'+line[:s]+'"'+",")

Third method:

file context manager

with open('somefile.txt', 'r') as f:

data = f.read()

# Iterate over the lines of the file

with open('somefile.txt', 'r') as f:

for line in f:

# process line

# Write chunks of text data

with open('somefile.txt', 'w') as f:

f.write(text1)

f.write(text2)

...

# Redirected print statement

with open('somefile.txt', 'w') as f:

print(line1, file=f)

print(line2, file=f)

Related: Several ways for python to write files _ 3 ways to read and write text files in python