Python Programming Unit - IV - Files
Python Programming Unit - IV - Files
UNIT IV - FILES
Dr. [Link]
Files
Two types of files – Text files and Binary files.
In text file, an End-of-Line (EOL) character is placed at the end of each
line.
An End-of-File (EOF) marker is placed after the final character, which
signals the end of the file.
Files
File Path
file path -- which is basically a route so that the user or the program knows where the file is
located.
Fully Qualified Path and Relative Path
Creating and Reading Text Data
open() – open a file.
file_handler = open(filename, mode) f1 = open(“[Link]",”x")
close() –
file_handler.close() [Link]()
Use of with Statements to Open and Close Files
with open (file, mode) as file_handler: with open(“[Link]”,w+) as f1,
open(“[Link]”,w+) as f2:
Statement_1 .
Statement_2 .
with open(“[Link]",”x") as f1:
for line in f1:
print(line)
[Link]()
Mode Description
File Object Attributes
When the Python open() function is called, it returns a file object called a file handler(f1).
Using this file handler, you can retrieve information about various file attributes. For
example,
1. >>> f1 = open("[Link]", "w")
2. >>> print(f"File Name is {[Link]}") File Name is [Link]
3. >>> print(f"File State is {[Link]}") File State is False
4. >>> print(f"File Opening Mode is {[Link]}") File Opening Mode is w
Attribute Description
[Link] It returns a Boolean True if the file is closed or False otherwise.
[Link] It returns the access mode with which the file was opened.
[Link] It returns the name of the file.
File Methods to Read and Write Data
When you use the open() function a file object is created. Here is the list of methods that
can be called on this object
If you have an object x and a file object f, which has been opened for writing, the simplest
way to pickle the object is, [Link](x, f)
The dump() method writes a pickled representation of object x to the open file object f.
If f is a file object, which has been opened for reading, then the simplest way to unpickle
the object is, x = [Link](f)
The load() method reads a pickled object representation from the open file object f and
return the reconstituted object hierarchy specified therein.
Pickling is the standard way to make Python objects that can be stored and reused by other
programs or by a future invocation of the same program;
Reading and Writing CSV Files
CSV (Comma Separated Values) format is the most common import and export format
for spreadsheets and databases. Since a comma is used to separate the values, this
file format is aptly named Comma Separated Values
Reading and Writing CSV Files
CSV files have .csv extensions
To read from a CSV file use [Link]() method. The syntax is,
[Link](csvfile)
To write to a CSV file, use the [Link]() method. The syntax is,
[Link](csvfile)
1. import csv
2. def main():
3. with open('[Link]', newline='') as csvfile:
4. csv_reader = [Link](csvfile)
5. print("Print each row in CSV file")
6. for each_row in csv_reader:
7. print(",".join(each_row))
8. if __name__ == "__main__":
9. main()
Python os and [Link] Modules
Python os module provides a portable way of using operating system dependent
functionality.
For accessing the filesystems, use the os module.
To manipulate paths, use the [Link] module.
Summary
Python supports two basic file types, namely text files and binary files.
• File objects can be used to read/write data to/from files. You can open a file with mode
'r' for reading, 'w' for writing, and 'a' for appending.
• The read(), readline(), and readlines() methods are used to read data from a file.
• The write() and writes() methods are used to write data to a file.
• The file object should be closed after the file is processed to ensure that the content
is saved properly.
• The dictionary data can be read and written to a CSV file using DictReader() and
DictWriter() classes.
• The os Module methods are used to perform some important processing on files.