Text Files
Understanding Text Files
Text files are the most common type of files used to store human-readable data. In Python, you can interact with text files using built-in functions and methods.
Opening a Text File
To work with a text file, you first need to open it using the open()
function:
Python
file =
open(
"filename.txt",
"r")
· filename: The name of the file you want to open.
· mode: The mode in which you want to open the file. Common modes are:
o
'r'
: Read mode (default)
o
'w'
: Write mode (creates a new
file or overwrites an existing one)
o
'a'
: Append mode (adds to the
end of an existing file or creates a new one)
o
'x'
: Create mode (creates a new
file, fails if the file already exists)
o
'r+'
: Read and write mode
Reading from a Text File
Once you have opened a file in read mode, you can read its contents using various methods:
· read(): Reads the entire contents of the file as a single string.
· readline(): Reads a single line from the file.
· readlines(): Reads all lines of the file and returns them as a list of strings.
Python
file =
open(
"my_file.txt",
"r")
content = file.read()
print(content)
file.close()
Writing to a Text File
To write to a text file, open it in write or append mode:
Python
file =
open(
"my_file.txt",
"w")
file.write(
"This is some text.\n")
file.close()
Closing a File
It's essential to close a file after you're done using it to release system resources:
Python
file.close()
Using the with
Statement
A more elegant and safer way to handle files is using the with
statement:
Python
with
open(
"my_file.txt",
"r")
as file:
content = file.read()
print(content)
The with
statement automatically closes the file when the block ends, even if
an exception occurs.
Additional Considerations
·
Encoding: Specify the encoding when
opening the file if you know the character encoding (e.g., open("file.txt", "r",
encoding="utf-8")
).
·
Error
handling:
Use try-except
blocks to handle potential
errors like file not found or permission denied.
·
File
modes:
Explore other file modes like 'rb'
for reading binary files.
By understanding these concepts, you can effectively work with text files in your Python programs.