Python provides some basic functions and methods to perform operations on a file
A file
object can be used to read and manipulate files
open
function - Open a file in Python To read or write a file, it has to be opened using Python's built-in open() function
This function creates a file object, which can then be utilized to call other methods associated with it
file object = open(file_name [, access_mode][, buffering])
file_name : string value denoting name of file to be accessed
access_mode : access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc
This is an optional parameter as the default file access mode is read (r
)
A list of possible values is provided in a table below
buffering - If the buffering value is set to 0, no buffering takes place
If value is 1, line buffering is performed while accessing a file
If value specified is an integer greater than 1, then it is taken as the buffer size
If negative, the buffer size is the system default, which is the default behavior
Here is a list of the different modes of opening a file :
Sr.No | Modes | Description |
---|---|---|
1 | r | Opens a file for reading only The file pointer is placed at the beginning of the file, by default This is the default access mode |
2 | rb | Opens a file for reading only in binary format File pointer is placed at the beginning |
3 | r+ | Opens a file for both reading and writing File pointer is placed at the beginning |
4 | rb+ | Opens a file for both reading and writing in binary format File pointer is placed at the beginning |
5 | w | Opens a file for writing only, overwriting any content in the file If file doesn't exist, it creates a new file |
6 | wb | Opens a file for writing only in binary format, and overwrites existing file If the file does not exist, creates a new file |
7 | w+ | Opens a file for both writing and reading, and overwrites existing file If the file does not exist, it creates a new file |
8 | wb+ | Opens a file for both writing and reading in binary format, and overwrites existing file If the file does not exist, it creates a new file |
9 | a | Opens a file for appending at the end of the file If the file does not exist, it creates a new file |
10 | ab | Opens a file for appending in binary format and places file pointer at the end of file If the file does not exist, it creates a new file |
11 | a+ | Opens a file for both appending and reading, and places file pointer at the end of file If the file does not exist, it creates a new file |
12 | ab+ | Opens a file for both appending and reading in binary format, and places file pointer at the end of file If the file does not exist, it creates a new file |
close()
method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done
Python automatically closes a file when the reference object of a file is reassigned to another file
It is considered a good practice to use the close() method to close a file
fileObject.close();
#!/usr/bin/python
# Open a file
fo = open("foo.txt","wb")
print"Name of the file: ", fo.name
# Close opened file
fo.close()
Output :
Name of the file: foo.txt
A file object, created by opening a file, contains information related to the file
Sr.No | Attribute | Description |
---|---|---|
1 | file.closed | Returns true if file is closed |
2 | file.mode | Returns access mode with which file was opened |
3 | file.name | Returns name of the file |
4 | file.softspace | Returns false if space explicitly required with print, true otherwise |
#!/usr/bin/python
# Open a file
fo = open("foo.txt","wb")
print("Name of the file: ", fo.name)
print("Closed or not : ", fo.closed)
print("Opening mode : ", fo.mode)
print("Softspace flag : ", fo.softspace)
Output :
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0
The file object provides a set of access methods to make our lives easier
We would see how to use read() and write() methods to read and write files
The write() method writes any string to an open file
Python strings can have binary data, apart from text data
write() method does not add a newline character ('\n') to the end of the string
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file
#!/usr/bin/python
# Open a file
fo = open("foo.txt","wb")
fo.write("Sometimes people cross lines \n Sometimes people don't\n")
# Close opened file
fo.close()
The above method would create foo.txt file and would write given content in that file and finally it would close that file
If you would open this file, it would have following content
Python is a great language.
Yeah its great!!
The read() method reads a string from an open file
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file
This method starts reading from the beginning of the file and if count is missing, then it tries to read until the end of file
Consider file foo.txt, assuming it is created as mentioned above
#!/usr/bin/python
# Open a file
fo = open("foo.txt","r+")
str = fo.read(10);
print"String read from file : ", str
# Close opend file
fo.close()
This produces following output:
String read from file : Sometimes people cross lines
tell()
method returns the current position in terms of bytes, within the file; in other words, the next read or write occurs at that many bytes from the beginning of the file
seek(offset[, from])
method changes the current file position
offset argument indicates the number of bytes to be moved
from argument specifies the reference position from where the bytes are to be moved
If from is set to 0, it uses the beginning of the file as the reference position and 1 uses the current position as the reference position and if it is set to 2 then the end of the file is taken as the reference position
Consider file foo.txt, as mentioned above
#!/usr/bin/python
# Open a file
fo = open("foo.txt","r+")
str = fo.read(10);
print("String read from file : ", str)
# Check current position
position = fo.tell();
print("Current file position : ", position)
# Reposition pointer to the beginning
position = fo.seek(0,0);
str = fo.read(10);
print("String read from file after seek() : ", str)
# Close opened file
fo.close()
Output :
String read from file : Sometimes people cross lines
Current file position : 10
String read from file after seek() : Sometimes people cross lines
Python os module provides methods that help to perform file-processing operations, such as renaming and deleting files
To use this module it has to be imported like -
import os
The rename() method takes two arguments, the current filename and the new filename
os.rename(current_file_name, new_file_name)
Example to rename an existing file test1.txt:
#!/usr/bin/python
import os
# Rename a file from file1.txt to filename2.txt
os.rename("file1.txt","filename2.txt")
The remove() method is used to delete files by supplying the name of the file as the argument
os.remove(file_name)
Example to delete an existing file file2.txt :
#!/usr/bin/python
import os
# Delete file file2.txt
os.remove("file2.txt")
Python has inbuilt functions to handle operations involving directories
The os module has methods to create, remove, and change directories
The mkdir() method of the os module is used to create directories in the current directory
It accepts the name of the directory to be created as argument
os.mkdir("newdir")
Example to create a directory Newfolder in the current directory :
#!/usr/bin/python
import os
# Create a directory "Newfolder"
os.mkdir("Newfolder")
The getcwd() method displays the current working directory
os.getcwd()
Example to get current directory :
#!/usr/bin/python
import os
# This returns location of the current directory
os.getcwd()
The chdir() method can be used to change the current directory
It takes as argument, the name of the directory that is to be made the current directory
os.chdir("new_dir_path_or_name")
Example to go to "/home/somedir" directory :
#!/usr/bin/python
import os
# Changing directory to "/home/somedir"
os.chdir("/home/somedir")
rmdir() method deletes the directory, which is passed as an argument to the method
Before removing a directory, all the contents in it should be removed
os.rmdir('dirname')
Example to remove "/tmp/test" directory
#!/usr/bin/python
import os
# This would remove "/tmp/test" directory.
os.rmdir("/tmp/test")
If fully qualified name of the directory is not provided, then it searches for that directory in current directory
It is recommended to use any of the functions mentioned above inside a try-except block