Python's file operating is so powerful that you may use python to operate your file system as shell did. In the following topics, I will do some introduction of python's file operations.
Package
We need to import some of the packages provided defaultly by python. All of it is essential and useful.
import os
Operations
Creation
Then we can focus on the file operations. First, let's see how to create a file:
file = open('file_to_operate', 'w')
There are several attributes to use in the open function:
- r -> (read)
- a -> (append)
- w -> (write)
And I think it is really easy to understand.
If you need to do it more safely, you could do this first:
if not os.path.exists('file_to_create'):
...
the exists function will tell you if in your working directory the file you wanna create is already in.
Read
Reading things from file can make our program run more flexible and easy to modify. It is also very easy to read characters from an existing file. You could also use the knowledge learnt above to check if the file to read exsits.
There are several function to implements this work. All of them is likely to each other, we choose two of them to make a discussion.
First,
str_content = file.read()
read() function is the basis function to read things from a file. You could read all the things out. Somethings like jsons can be easily obtained and used in the following program.
Second,
str_content = file.readlines()
readlines() function just do a little more things to the read operation. It provides you a line-style view of the file. If your file luckily stores with lines, you would really appreciate it.
Attention: readlines function would also count \n(or \r\n in windows) into a string line, you should take this into account.
Close
If you have already learnt c/cpp before you learn python, this close operation must be familiar to you. The file handler is a resource of an system, we need to return it to the os if you no longer require it.
f.close()
Easy, right?
The topic of python file operation would be updated when I encounter some more diffult requirements.