In most of the applications, operating with files like reading and writing is common thing. Almost every programming language provides an application programming interface using which we can seamlessly interact with and operate on files and directories. Python also provides many modules and methods with which working with files becomes easy for a developer. So, lets get started and see what Python has to offer to interact with files and directories.
File Reading and Writing
To read from or write into a file in Python, we first need to open a file and get its underlying stream. To open a file for reading/writing, Python provides us with open(..) method. Lets see the below example.
f = open("file-demo-read.txt", "r")
data = f.read()
print(data)
f.close()
The open(..) method is used to open a file. It takes two parameters as you can see in the above example.
- The path of the file
- Mode in which file needs to be opened
There are different modes of opening a file.
Mode | Description |
---|---|
r | To open a file in read only mode. |
w | To open a file in write only mode. |
r+ | To open a file in both read and write mode (cannot truncate a file). |
w+ | To open a file in both read and write mode (can truncate a file). |
a | To open a file for appending. |
rb, wb, rb+, wb+, ab | The above 5 modes are appended with b option. The 'b' option is used to open a file in read/write/read-write/append mode in binary format. |
The open(..) method returns a stream object which we use to read from and write to. The read() method reads the contents of the stream. If no parameter value is provided to the read method then it will read the entire content of the file. Otherwise, it takes a numeric value as a parameter which defines the number of characters to read from the stream.
* There is one clean way of reading and writing files, and should be used as a practice. We do it by with clause.
with open("file-demo-read.txt", "r") as f:
data = f.read()
print(data)
There are two benefits of using this style of file opening. First, its clean. Second, the close method will be implicitly called just before exiting with block. So we don't need to call the close method.
There is another method in file's stream object readline() which is use to read one line at a time. the following code will read first line from the file.
with open("file-demo-read.txt", "r") as f:
data = f.readline()
print(data)
The file's stream object has a method readlines() will read all lines in the file.
To write into a file, we need to use write() method of the file stream object. See the example below.
f = open("file-demo-write.txt", "r+")
f.write("This is a sample text.")
f.close()
File positions
To read a file from a particular position we use seek(..) method of the stream object.
f = open("file-demo-write.txt", "r")
f.seek(5)
data = f.readline()
print(data)
# Output -> is a sample text.
Previously in the file "file-demo-write.txt", we have written a text "This is a sample text". From this text, the function seek(..) will forward the stream cursor to 5th position. Now when we call readline() method on the stream object it will start reading from 5th position. The output will be "is a sample text."
The following code will reset the stream's cursor position to 0.
f.seek(0)
data = f.readline()
print(data)
# Output -> This is a sample text.
File-system operations
Every operating system has its own file system and file operations to operate functions like copy, move, renaming, removing files and directories, getting files and directories information. Python provided us with a package called os which does all these operations seamlessly. Lets see with the help of few examples.
Create a directory under current working directory.
os.mkdir("demo")
Rename this directory.
os.rename("demo", "demo-dir")
Change current working directory to demo-dir.
os.chdir("demo-dir")
Print current working directory
curr_dir = os.getcwd()
print(curr_dir)
Create a file under this current directory.
f = open("demo.txt","w+")
f.close()
Rename this file.
os.rename("demo.txt", "demo-file.txt")
Create two directory under this directory.
os.mkdir("demo-sub-dir-1")
os.mkdir("demo-sub-dir-2")
List all files and directories.
dir_list = os.listdir()
print(dir_list)
Get the statistics of a directory. Current directory in the case below.
stat = os.stat(".")
print(stat)
Disclaimer : Executing these examples incorrectly (modifying code and then executing) may delete your important or system files. We do not take any guarantee if anything happens to your machine or some files gets deleted. Be sure to read about these functions first and try executing these in the jupyter notebook as mentioned in below link.
Python jupyter notebook for code examples
Access Jupyter notebook for this chapter here:
Jupyter Notebook - Working with files