Introduction to Files
- Files are used to store data persistently on your computer's storage.
- Python provides built-in functions to work with files (e.g.,
open()
,read()
,write()
,close()
).
Types of Files
-
Text File:
- Stores data as plain text characters.
- Examples:
.txt
,.py
,.html
,.md
- Can be easily read and edited with a text editor.
-
Binary File:
- Stores data in a binary format (a sequence of bytes).
- Examples:
.jpg
,.png
,.mp3
,.exe
,.pdf
- Requires specialized software to open and view.
-
CSV File (Comma-Separated Values):
- Stores data in a tabular format where values are separated by commas.
- Often used for spreadsheets and databases.
- Example:
.csv
File Handling in Python
Python
# Opening a file in read mode
file = open("my_file.txt", "r")
contents = file.read()
print(contents)
file.close()
# Opening a file in write mode (creates a new file or overwrites existing)
file = open("new_file.txt", "w")
file.write("This is a new line.")
file.close()
File Paths
-
Absolute Path:
- The full path to the file, starting from the root directory of the file system.
- Example:
/Users/username/Documents/my_file.txt
-
Relative Path:
- The path to the file relative to the current working directory.
- Example:
data/my_file.txt
(if the file is located in thedata
folder within the current working directory)
Diagram
Key Points
-
open()
function:- Takes two arguments: the file name and the mode (
"r"
for reading,"w"
for writing,"a"
for appending, etc.). - Returns a file object that can be used to interact with the file.
- Takes two arguments: the file name and the mode (
-
read()
method:- Reads the contents of the file.
-
write()
method:- Writes data to the file.
-
close()
method:- Closes the file and releases the resources associated with it.
-
with
statement:- A more elegant way to handle files, as it automatically closes the file even if an exception occurs.
Python
with open("my_file.txt", "r") as file:
contents = file.read()
print(contents)
Note: This is a basic introduction to file handling in Python. You can explore more advanced topics like reading and writing binary files, working with CSV files using the csv
module, and handling file-related exceptions.
No comments:
Post a Comment