Text File in Python Notes Class 12

csitzone.com

Text Files 

  • Text files store data in text form only.

  • They use ASCII or Unicode characters.

  • Each line ends with EOL (End of Line) — usually \n.

  • To work on a file: open → write → save → close.

  • You can also open an existing file to read or edit data.

  • Same method is used in File Handling / Data File Handling.

  • Example: notes.txt or data.txt

  •      Reading from a File

       Methods to Read: It includes three function to read which are given as under with example.

Method Description
1. read() Reads entire file content as a string.
2. readline() Reads one line at a time.
3. readlines() Reads all lines into a list.

 

Examples:

     1. read( )

f = open("data.txt", "r")
print(f.read())          # entire file
f.close()

     2.  readline ( )

f = open("data.txt", "r")
print(f.readline())      # one line
f.close()

     3. readlines ( )

f = open("data.txt", "r")
print(f.readlines())     # list of lines
f.close()

  •     Writing to a File

    Methods to Write: It includes two function to write, which are given as under with example. Both methods are used to write data into a text file

    1. Using write() method: 

  • Used to write a single string into a file.

  • It overwrites existing content if the file is opened in 'w' mode.

  • No automatic newline (\n) is added — you must add it manually.

f = open("data.txt", "w")
f.write("Hello, this is a file handling example.")
f.close()

      2. Using writelines() method:

  • Used to write multiple lines (list or tuple of strings) into a file.

  • It writes all strings together — doesn’t add \n automatically.

  • You must include \n in each string manually if you want new lines.

lines = ["Line1\n", "Line2\n", "Line3\n"]
f = open("data.txt", "w")
f.writelines(lines)
f.close()

     Difference between write() and writelines()-

Feature write () writelines()
Data type Single string List or tuple of strings
Newline (\n) Must add manually Must add manually
Writes One string at a time Multiple strings at once
Example f.write("Hello\n") f.writelines(["A\n", "B\n"])

 

  • Appending to a File

        Methods to Appending- 

  • Appending means adding new data at the end of an existing file without deleting old data.

  • In Python, this is done using the 'a' mode in the open() function.

  • If the file already exists, new data is added at the end.

  • If the file does not exist, Python creates a new file.

  • Old data is not erased (unlike 'w' mode).

  • Cursor always stays at end of file when opened in 'a' mode.

#using write function

f = open("data.txt", "a")
f.write("\nThis is new data added at the end.")
f.close()

# using writelines function

f = open("data.txt", "a")
lines = ["\nLine 3", "\nLine 4"]
f.writelines(lines)
f.close()

  r+, w+ and a+ modes in Text File

Leave a Reply

Your email address will not be published. Required fields are marked *