Write data to file
The
write()
method is used to write data to a file. Numeric data must be converted to a string. This can be done either with the
format()
method or with the
str()
.
method
Multiline Files
When working with multi-line files, you need to know when the data in the file runs out. To do this, you can use the feature of the
readline()
methods: if the file cursor points to the end of the file, then the
readline()
method returns an empty string, which is perceived as a false boolean value:
while True:
s = Fin.readline()
if not s: break # if an empty string is received when reading a string,
# the loop ends with a break statement
print(s, end="") # disable newline, because when reading a line from a file
# newline character "\n" saved
Other ways to read data from multiline files
1. Immediately all the data in the list.
Fin = open("input.txt")
list_strings = Fin.readlines()
# read all lines at once
Fin.close()
for s in list_strings:
print(s, end="")
2. Using the construction with-as
. In this case, the file is closed automatically after the end of the cycle.
with open("input.txt") as Fin:
for s in Fin:
print(s, end="")
This construct ensures that the file is closed.
3. A way to iterate over strings in the style of the Python language (it is recommended to use this method). In this case, the file is also closed automatically.
for s in open("input.txt"):
print(s, end="")