Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

File Handling in Python

The document provides an overview of file handling in Python, detailing types of files, opening modes, and methods for reading and writing files. It explains various file operations such as reading, writing, seeking, and copying files, as well as renaming files using the os module. Additionally, it covers important methods and their syntax for effective file manipulation in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

File Handling in Python

The document provides an overview of file handling in Python, detailing types of files, opening modes, and methods for reading and writing files. It explains various file operations such as reading, writing, seeking, and copying files, as well as renaming files using the os module. Additionally, it covers important methods and their syntax for effective file manipulation in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

FILE HANDLING IN

PYTHON

Python File I/O – Introduction

What is File?
A file is the collection of
A file is a location on disk that stores related information and has a name.
Types of Data File
1. Text File:- Text file contains textual information in the form of alphabets,
digits, special characters and symbols as a text document or plain text
document. Text file store data in sequential bytes but bits in text file
represent characters.
Text files are of two types
a) Plain text files: - These files store End of Line (EOL) marker at the end
of each line to represent line break and an End of File (EOF) at the end of
the file to represent end of file.

Compiled By: Riteash Kumar Tiwari (VBPSC, Prayagraj)Page 1


b) Rich Text File:-These files also follow the same schema as the as the
plain text files but may also store text related information like text color,

test style, font style etc.

2. Binary files: - Binary file are those typical file that store data in the form
of sequence of bytes (compiled version of text file) grouped into 8 bit or
sometimes 16 bit. This bit represents custom data and such files can store
multiple types of data (images, audio, text etc.) under a single file.

Opening File
To deal Python file I/O, we have a built-in function open () with a File Object
(should be a valid identifier) in the following mode.
Syntax:-File_Object=open(“FileName”, “Opening_Mode”)
Opening Modes
While opening Python file, we can declare our intentions by choosing a mode. We
have the following modes:
Mode Description
r To read a file (default)
w To write a file; Creates a new file if it doesn’t exist, truncates if it does
x Exclusive creation; fails if a file already exists
a To append at the end of the file; create if doesn’t exist
t Text mode (default)
b Binary mode
+ To open a file for updating (reading or writing)
Examples
#To read and write in binary mode
>>> Myfile=open(“Example.txt”,'r+b')
>>> Myfile=open(“Example.txt”,'a')
Note:-Myfile is the file object, also called File Handle Example.txt is the name
of file and “r+b” is the Opening Mode.
When Python File Doesn’t Exist
Finally, if you try opening Python file that doesn’t exist, the interpreter will throw
a FileNotFoundError.

Compiled By: Riteash Kumar Tiwari (VBPSC, Prayagraj)Page 2


>>> Myfile=open('abc.txt')
Output:-No such file or directory: ‘abc.txt’
Closing File
>>> Myfile.close()
Reading File in Python
To read the contents of a Python file, we can do one of these:

Python File I/o – Python Read File

Suppose a file Example.txt contains:


‘Get groceries\nOrganize room\nPrint labels\nWrite
article\nStudy for examLearn to cook\nLearn to cook’

a. The read() Method


We can use the read() method to read what’s in a Python file.
1. >>> Myfile= open(“Example.txt”)
2. >>>Myfile.read()

When we provide an integer argument to read(), it reads that many characters


from the beginning of the Python file.
1. >>> Myfile =open(“Example.txt”)
2. >>> Myfile.read(5)

Now when we call read() without any arguments, it reads the rest of the Python
file.

Compiled By: Riteash Kumar Tiwari (VBPSC, Prayagraj)Page 3


1. >>> Myfile.read()

Notice that it prints a ‘\n’ for a newline. And when we yet read it, it prints an
empty string, because the cursor has reached the end of the Python file.
1. >>> Myfile.read()
2. ''
3. >>> Myfile.close()

b. Seek() and tell()


Okay, jokes apart, these two methods let us reposition the cursor and find its
position. tell() tells us where the cursor is.
1. >>> Myfile =open(“Example.txt”)
2. >>> Myfile.read(5)
3. >>> Myfile.tell()
Output: - 5
seek() takes an integer argument, and positions the cursor after that many
characters in the Python file. Along with that, it returns this new position of the
cursor.
1. >>> Myfile.seek(0)
2. >>> Myfile.read()

c. Using Python For-loop


We can simply use a for-loop to iterate on a file. This is the beauty of Python- it
simplifies everything.

1. >>> for line in open(“Example.txt”):


2. >>>print(line,end='')

We used the ‘end’ parameter to prevent the interpreter from adding extra
newlines to each output. Otherwise, the output would have looked like this:
>>> for line in open(“Example.txt”):
>>>print(line)

d. Readline()
Alternatively, the method readline() lets us read one line at a time. Simply put, the
interpreter stops after every ‘\n’.

Compiled By: Riteash Kumar Tiwari (VBPSC, Prayagraj)Page 4


>>> Myfile =open(“Example.txt”)
>>> Myfile.readline()
Output: - ‘Get groceries\n’
>>> Myfile.readline()
Output: - ‘Organize room\n’
>>> Myfile.readline()
Output: - ‘Print labels\n’
>>> Myfile.readline()
Output: - ‘Write article\n’
>>> Myfile.readline()
Output: - ‘Study for exam\n’
>>> Myfile.readline()
Output: - ‘Learn to cook’
>>> Myfile.readline()

>>> Myfile.readline()

e. Readlines()
Lastly, the readlines() method reads the rest of the lines/file.
1. >>> Myfile.seek(0)
1. >>> Myfile.read(5)
Output: - ‘Get g’
1. >>> Myfile.readlines()
Output: - [‘Groceries\n’, ‘Organize room\n’, ‘Print labels\n’, ‘Write article\n’,
‘Study for exam\n’, ‘Learn to cook’]

Writing to File
To write a Python file, we use the write() method.
1. >>> Myfile =open(“Example.txt”,'a')
2. >>> Myfile.write('\nLearn to cook')
Output: - 14
1. >>> Myfile.close()
When we checked in the file (refreshed it), we found:
Get groceries
Organize room
Print labels
Write article
Study for exam

Compiled By: Riteash Kumar Tiwari (VBPSC, Prayagraj)Page 5


Learn to cook

Concluding, you can use ‘w’, ‘a’, or ‘x’. The ‘w’ erases the content and writes over it.
So, be careful with it. Also, write() returned 14 here because it appended 14
characters to Python file.
But you can’t read a Python file if you open it in ‘a’ mode.
1. >>> Myfile =open(“Example.txt”,'a')
2. >>> Myfile.read()
Error: - Myfile.read()
io.UnsupportedOperation: not readable
To get around this, you’d have to use ‘a+r’.

Some More File Methods in Python


detach()
This detaches the underlying binary buffer from TextIOBase and returns it.
1. >>> Myfile.detach()
<_io.BufferedRandom name=’C:\\Users\\lifei\\Desktop\\ Example.txt’>
1. >>> Myfile.read()
Error: - Traceback (most recent call last):
File “<pyshell#171>”, line 1, in <module>
Myfile.read()
ValueError: underlying buffer has been detached
Note:-After detaching from the buffer, when we try to read the file, it raises a
ValueError.
fileno()
fileno() returns a file descriptor of the file. This is an integer number.
1. >>> Myfile =open('C:\\Users\\lifei\\Desktop\\ Example.txt ')
2. >>> Myfile.fileno()
flush()
Writes the specified content from the program buffer to the operating system
buffer in event of a power cut.
1. >>> Myfile.flush()
read(n)
This lets us read n characters from a file.
1. >>> Myfile =open('C:\\Users\\lifei\\Desktop\\ Example.txt ')
2. >>> Myfile.read(5)
Output: - ‘Get g’

Compiled By: Riteash Kumar Tiwari (VBPSC, Prayagraj)Page 6


readable()
This returns True if the object is readable.
1. >>> Myfile.readable()
Output: - True
1. >>> Myfile.close()
2. >>> Myfile=open('C:\\Users\\lifei\\Desktop\\Example.txt','a')
3. >>> Myfile.readable()
Output: - False
1. >>> Myfile.close()
readline(n=-1)
readline() reads the next line.
1. >>> Myfile=open('C:\\Users\\lifei\\Desktop\\Example.txt')
2. >>> Myfile.readline()
Output: - ‘Get groceries\n’
1. >>> Myfile.readline(5)
Output: - ‘Organ’
1. >>> Myfile.readline(2)
Output: - ‘iz’
1. >>> Myfile.readline()
Output: - ‘e room\n’
1. >>> Myfile.readline(5)
Output: - ‘Print’
1. >>> Myfile.readline(-1)
Output: - ‘ labels\n’
readlines()
This one reads the rest of the lines.
1. >>> Myfile.seek(0)
1. >>> Myfile.readlines(0)
Output: - [‘Get groceries\n’, ‘Organize room\n’, ‘Print labels\n’, ‘Write article\n’,
‘Study for exam\n’, ‘Learn to cookWrite to the end of the fileHi’]
1. >>> Myfile.seek(0)
1. >>> Myfile.readlines(1)
[‘Get groceries\n’]
seek()
Lets us reposition the cursor to the specified position.
1. >>> Myfile.seek(3)
Output: - 3
Compiled By: Riteash Kumar Tiwari (VBPSC, Prayagraj)Page 7
seekable()
This returns True if the file stream supports random access.
1. >>> Myfile.seekable()
Output: - True
tell()
Tells us the current position of the cursor.
1. >>> Myfile.tell()
Output: - 118
truncate()
Resizes the file. You must open your file in a writing mode for this.
We have Example.txt sized 118 bytes currently. Let’s resize it to 100 bytes.
1. >>> Myfile=open('C:\\Users\\lifei\\Desktop\\Example.txt','a')
2. >>> Myfile.truncate(100)
Output: - 100
This returned the new size. We even went to our desktop and checked, it indeed
resized it. But in doing this, it truncated some of the content of the file from the
end.
1. >>> Myfile=open('C:\\Users\\lifei\\Desktop\\Example.txt')
2. >>> Myfile.read()
Output: - ‘Get groceries\nOrganize room\nPrint labels\nWrite article\nStudy
for exam\nLearn to cookWrite to the’
When we provide no argument, it resizes to the current location.
writable()
This returns True if the stream can be written to.
1. >>> Myfile=open('C:\\Users\\lifei\\Desktop\\Example.txt')
2. >>> Myfile.writable()
Output: - False
write(s)
This method takes string ‘s’, and writes it to the file. Then, it returns
the number of characters written.
1. >>> Myfile=open('C:\\Users\\lifei\\Desktop\\Example.txt','a')
2. >>> Myfile.write('\nWrite assignment')
Output: - 17
writelines()
Writes a list of lines to a file.
Myfile=open('C:\\Users\\lifei\\Desktop\\Example.txt')
Compiled By: Riteash Kumar Tiwari (VBPSC, Prayagraj)Page 8
Myfile.writelines([‘\nOne’,’\nTwo’,’\nThree’])
print(todo.read())

Output: -
Get groceries
Organize room
Print labels
Write article
Study for exam
Learn to cookWrite to the
Write assignment
One
Two
Three

Copying Files in Python


Here, are main 4 categories of ways through which Python Copy a file.
a. Using Python OS Module
There are two ways to copy a file in Python- the popen() method and the system()
method. Let’s discuss them.

i. popen()
The popen() method returns a file object that connects to a pipe. In mode ‘w’, we
can write to it, and in mode ‘r’, we can read from it (‘r’ is the default).
Syntax:-
os.popen(command[, mode[, bufsize]])
Here, command is the command we use, and mode is ‘r’ or ‘w’, as discussed
previously. When bufsize is 0, there is no buffering. When it is 1, there is line
buffering when accessing a file. When it is an integer greater than 1, there is

Compiled By: Riteash Kumar Tiwari (VBPSC, Prayagraj)Page 9


buffering with the indicated buffer size. For a negative value, a default buffer size
is used.
We have a file labeled ‘1.txt’ on the Desktop. We use the following code:
Example:-
1. >>> import os
2. >>> os.chdir('C:\\Users\\lifei\\Desktop')
3. >>> os.popen('copy 1.txt 2.txt')
As you can see, this creates a new file labeled ‘2.txt’ on the Desktop. This has the
same contents as 1.txt.
ii. system()
The system() method lets us execute a command as a string in a subshell. Any
output the command generates goes to the interpreter standard output stream.
Syntax:-
os.system(command)
Example:-
1. >>> import os
2. >>> os.chdir('C:\\Users\\lifei\\Desktop')
3. >>> os.system('copy 1.txt 2.txt')
We can see the same action with this method. It copies the contents of a file 1.txt
into a new file 2.txt.

Renaming Files in Python

os.rename()
Compiled By: Riteash Kumar Tiwari (VBPSC, Prayagraj)Page 10
OS.rename() is used to python rename file. Like the name suggests, it lets us
rename files and directories.
Syntax of os.rename()
os.rename(src, dst)
Here, src is the source file or directory. dst is the destination file or directory. It
doesn’t return any value.
os.rename() Example
In the following example, we rename the folder ‘NewFolder’ to ‘Photos’.
1. >>> import os,sys
2. >>> os.chdir('C:\\Users\\lifei\\Desktop')
3. >>> print(f"We have: {os.listdir()}")
We have: [‘0.jpg’, ‘1.txt’, ‘Documents’, ‘NewFolder’, ‘Today.txt’]
1. >>> os.rename('NewFolder',’Photos’) #This does the renaming
2. >>> os.listdir()
[‘0.jpg’, ‘1.txt’, ‘Documents’, ‘Photos’, ‘Today.txt’]

As you can see, this has renamed the directory ‘NewFolder’ to ‘Photos’. At the time
of writing this article, we tried to rename the directory to the name ‘Documents’.
This raised the following error:
1. >>> os.rename('NewFolder','Documents')
FileExistsError: [WinError 183] Cannot create a file when that file already
exists: ‘NewFolder’ -> ‘Documents’

Renaming Multiple Files


1. >>> import os
2. >>> os.chdir('C:\\Users\\lifei\\Desktop\\Photos')
3. >>> i=1
4. >>> for file in os.listdir():
5. src=file
6. dst="Dog"+str(i)+".jpg"
7. os.rename(src,dst)
8. i+=1

Renaming File (Single File)


Sometimes, we may want to rename just one file from tens or hundreds. We can
search for it and then use Python to rename it. In the following code, we rename
‘Dog7.jpg’ to ‘SeventhDog.jpg’.
1. >>> for file in os.listdir():
2. src=file
Compiled By: Riteash Kumar Tiwari (VBPSC, Prayagraj)Page 11
3. if src=='Dog7.jpg':
4. dst="Seventh Dog.jpg"
5. os.rename(src,dst)

Compiled By: Riteash Kumar Tiwari (VBPSC, Prayagraj)Page 12

You might also like