Nearby lessons

78 of 108

Python - Write Files

Detailed Tutorial Notes

Eg 2:

1) f=open("abcd.txt",'w')
2) list=["sunny\n","bunny\n","vinny\n","chinny"]
3) f.writelines(list)
4) print("List of lines written to the file successfully")
5) f.close()

abcd.txt:

sunny

bunny

vinny

chinny

Note: while writing data by using write() methods, compulsory we have to provide line

seperator(\n),otherwise total data should be written to a single line.

Reading Character Data from text files:

We can read character data from text file by using the following read methods.

read() To read total data from the file

read(n)  To read 'n' characters from the file

readline() To read only one line

readlines() To read all lines into a list

Eg 1: To read total data from the file

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
sunny
bunny
chinny
vinny

Eg 2: To read only first 10 characters:

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
sunny
bunn

Eg 3: To read data line by line:

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
sunny
bunny
chinny

Eg 4: To read all lines into list:

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
sunny
bunny
chinny
vinny

Eg 5:

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
sun
ny

11)

12) bunn
13) Remaining data

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Python - Append Files