0% found this document useful (0 votes)
2 views4 pages

Text File Notes

The document provides an overview of text file handling in Python, detailing how to open, read, write, and close files using various modes. It explains methods such as read(), readline(), readlines(), write(), and writelines(), along with examples for each. Additionally, it highlights the use of the 'with' statement for automatic file closure and the need to convert non-string data to strings before writing.

Uploaded by

dktanishq17
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

Text File Notes

The document provides an overview of text file handling in Python, detailing how to open, read, write, and close files using various modes. It explains methods such as read(), readline(), readlines(), write(), and writelines(), along with examples for each. Additionally, it highlights the use of the 'with' statement for automatic file closure and the need to convert non-string data to strings before writing.

Uploaded by

dktanishq17
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Text File Handling

Opening a File
A file can be opened using the open() func on:
file_object = open(filename, mode)
Example:
f = open("[Link]", "w")
A file object (or file handle) is a reference to a file stored on disk.
Modes of opening a file:
• 'r' – Read mode (default) •'r+' – Read and write mode
• 'w' – Write mode (overwrites the file) •'w+' – Write and read mode (creates a new file or
• 'a' – Append mode (adds data to the end of the overwrites an exis ng one)
file) •'a+' – Append and read mode

Note: If the mode is not men oned, Python opens the file in read ('r') mode by default.

File Path
The file "[Link]" should be present in the current working directory.
If it is located in another directory, specify the full path of the file.
When specifying a path, avoid using a single backslash (\) as it is treated as an escape character.
Use either double backslashes (\\) or a raw string (r" ") to represent file paths.
Examples:
f = open("c:\\users\\python\\[Link]")
# or
f = open(r"c:\users\python\[Link]")

Closing a File
file_object.close()
The close() method is used with a file handle to close the file and free system resources.
Note that open() is a built-in func on, while close() is a method of the file object.

I. READING FROM TEXT FILES:

Func on Returns Descrip on


read() String Reads the en re file content as a single string
readline() String Reads one line at a me
readlines() List Reads all lines and stores them in a list

Example:
Consider the file [Link], which has 3 lines.
The sun sets in golden hue,
The sky turns deep and blue,
Dreams awaken, bright and new.

1
1. read()
reads the en re file as one single string (including newline characters \n).

f = open("[Link]", "r") Output:


data = [Link]() "The sun sets in golden hue,
print(data) The sky turns deep and blue,
[Link]() Dreams awaken, bright and new."
 [Link]() reads the en re file as one single string, including newline characters (\n).
 Prin ng data will display all three lines exactly as they appear in the file.
[Link](n):
n is op onal. If specified, it reads n characters from the file. If omi ed, it reads the en re file.
data=[Link](3). Now, if you give print(data), it will print "The"

Spli ng the string into words


A er reading the file, you can use the split() method to separate the string into individual words.
data = [Link]() Output:
words = [Link]() ['The', 'sun', 'sets', 'in', 'golden', 'hue,', 'The', 'sky',
print(words) 'turns', 'deep', 'and', 'blue,', 'Dreams', 'awaken,',
'bright', 'and', 'new.']
• split() breaks the string at every space or newline.
• The result is a list of words, which can be processed like any other Python list.

2. Using readline()
f = open("[Link]", "r") Explana on:
line1 = [Link]()  Each call to readline() reads one line at a me from the file.
line2 = [Link]()  The newline character (\n) at the end of each line is also read and
line3 = [Link]() included in the string.
print(line1)  A er the last line, calling readline() again will return an empty string ('').
print(line2) Output:
print(line3) The sun sets in golden hue,
[Link]() The sky turns deep and blue,
Dreams awaken, bright and new.

Using a loop with readline()


You can read all lines one by one using a loop:
f = open("[Link]", "r")
line = [Link]()
while line:
print(line, end="") # end="" avoids extra blank lines
line = [Link]()
[Link]()

2
[Link](n)
 If n is specified, it reads up to n characters from the current line.
 It does not automa cally move to the next line unless called again.

3. Using readlines()
f = open("[Link]", "r")  Explana on:
lines = [Link]() readlines() reads all lines at once and stores them as a list of
print(lines) strings.
[Link]() Each element of the list represents one line from the file
(including \n).
Output:  Each line is now an element in the list.
['The sun sets in golden hue,\n', You can loop through the list to access lines individually:
'The sky turns deep and blue,\n', for line in lines:
'Dreams awaken, bright and
print(line, end="")
new.\n']

II. WRITING TO TEXT FILES


1. Wri ng Data to a File
To write data into a text file, open it in write mode ('w') or append mode ('a').
f = open("[Link]", "w")  'w' mode creates a new file or overwrites an exis ng file.
[Link]("Python is simple.\n")  The write() method writes data as a string into the file.
[Link]("It is powerful.\n")  Newline characters (\n) must be added manually if you
[Link]("File handling is easy!") want line breaks.
A er running this code, the file [Link] will contain:
[Link]() Python is simple.
It is powerful.
File handling is easy!

III. Appending Data to an Exis ng File


f = open("[Link]", "a")  'a' mode adds new content at the end of the file.
[Link]("\nPython supports many data types.")  Exis ng data in the file remains unchanged.
Now [Link] will contain:
[Link]()
Python is simple.
It is powerful.
File handling is easy!
Python supports many data types.

3
Wri ng Mul ple Lines
Instead of calling write() many mes, you can use writelines().
f = open("[Link]", "w")  writelines() writes a list of strings to the file.
lines = [  Each element in the list is wri en exactly as
"The sun sets in golden hue,\n", given.
"The sky turns deep and blue,\n",  You must include \n at the end of each line if you
want line breaks.
"Dreams awaken, bright and new.\n" The file [Link] now contains:
] The sun sets in golden hue,
[Link](lines) The sky turns deep and blue,
[Link]() Dreams awaken, bright and new.

Using with Statement


Instead of manually closing the file, you can use the with statement.
It automa cally closes the file once the block is executed.
with open("[Link]", "w") as f:
[Link]("Python makes file handling simple!\n")
[Link]("Using 'with' automa cally closes the file.")
No need to call [Link]() explicitly.

Wri ng Non-String Data


The write() func on accepts only strings.
To write numbers or other data types, convert them to a string using str ().
f = open("[Link]", "w")
num = 25
[Link]("The number is " + str(num))
[Link]()
 Wri ng integers or floats directly (without conver ng) will cause an error.

Summary of File Wri ng Methods

Method Used With Descrip on


write(str) String Writes a single string to the file
writelines(list) List of strings Writes mul ple strings to the file
with open() Any mode Automa cally closes the file a er use

Example: Combining Read and Write


# Copy contents from one file to another
with open ("[Link]", "r") as f1, open ("[Link]", "w") as f2:
data = [Link]()
[Link](data)
 Reads data from [Link] and writes it into [Link].
 Both files are closed automa cally a er execu on.

You might also like