0% found this document useful (0 votes)
18 views25 pages

Python Programming Unit - IV - Files

The document covers Python file handling, detailing two types of files: text and binary. It explains how to create, read, and write files using various methods, including the use of the 'with' statement for automatic file closure. Additionally, it discusses the CSV file format and the use of the os module for file system operations.

Uploaded by

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

Python Programming Unit - IV - Files

The document covers Python file handling, detailing two types of files: text and binary. It explains how to create, read, and write files using various methods, including the use of the 'with' statement for automatic file closure. Additionally, it discusses the CSV file format and the use of the os module for file system operations.

Uploaded by

Kavitha Donepudi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

PYTHON PROGRAMMING

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

 read() -- file_handler.read([size]) -- This method is used to read the contents of a file up to


a size and return it as a string. The argument size is optional, and, if it is not specified, then
the entire contents of the file will be read and returned.
 print([Link](2))
 readline() -- file_handler.readline() -- This method is used to read a single line in file.
 print([Link](), end=“ ")
 readlines() -- file_handler.readlines() -- This method is used to read all the lines of a file as
list items.
 print([Link](), end=“ ")
 write() -- file_handler.write(string) -- This method will write the contents of the string to the
file, returning the number of characters written. If you want to start a new line, you must
include the new line character.
 [Link]("Moon is a natural satellite")
File Methods to Read and Write Data

 writelines() -- file_handler.writelines(sequence) -- This method will write a


sequence of strings to the file.
 [Link](["Moon is a natural satellite", " ", "of the earth"])
 tell() -- file_handler.tell() -- This method returns an integer giving the file
handler’s current position within the file, measured in bytes from the beginning of
the file.
 [Link]()
 seek() -- file_handler.seek(offset,from_what) -- This method is used to change the
file handler’s position. The position is computed from adding offset to a reference
point. The reference point is selected by the from_what argument. A from_what
value of 0 measures from the beginning of the file, 1 uses the current file position,
and 2 uses the end of the file as the reference point. If the from_what argument is
omitted, then a default value of 0 is used, indicating that the beginning of the file
itself is the reference point.
 [Link](5)
File Methods to Read and Write Data
File Methods to Read and Write Data
Reading and Writing Binary Files
The Pickle Module
 Pickle -- This is a module that can take almost any Python object and convert it to a string
representation; this process is called pickling.
 Reconstructing the object from the string representation is called unpickling.

 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)

 The syntax for writerow() method is,


 [Link](row)
Reading and Writing CSV Files
 The syntax for writerows() method is,
 [Link](rows)

 The syntax for DictReader is,


 class csv. DictReader(f, fieldnames=None, restkey = None)

 The syntax for DictWriter is,


 class csv. DictWriter(f, fieldnames, extrasaction=‘raise’)
Reading and Writing CSV Files

 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.

You might also like