内容简介:The usage of file system is an important thing in the field of computer science. It is the most common method used to store required information in various formats. Usually, every programmer will use standard input output methods to test a logical concept.
The usage of file system is an important thing in the field of computer science. It is the most common method used to store required information in various formats. Usually, every programmer will use standard input output methods to test a logical concept. But, In the real time computing systems the standard input output operations is not only enough. When we use standard IO method in a program, the output will remain until the execution ends. File system is the best solution to store the information permanently in a memory device of a computer. This article will help you to understand the basics of file handling and advanced functions in file handling in python.
A Computer File
A computer file is a virtual environment that acts as a container for various types of information. Consider the real world, we have a lot of stuffs such as papers and books to store information. The computer needs a system same as that. The file system combines various files in a memory device with the help of directory. Directory of a file is a string that denotes where the file is stored in the memory disc.
The directory can be considered as the address of the file. A file can be stored in different folders in a drive. Each folder is separated by a forward slash (/). A file name will contain two parts. They are file name and extension. File name is a unique string used to name the file. The extension is the suffix used after the file name to denote the type of file. The structure of a file directory is given below.
The file name and the extension must be separated by a dot. The file name should not contain any special character in it. The example extensions are .mp4, .mp3.
Files in Python
Even though we have various file formats in our computer, the in-built methods in python can handle two major types of files. The types are text files and binary files. The text and binary files has .txt and .bin as their extensions respectively. We have to understand both types of files. Text files are used to store human readable information whereas the binary files contains computer readable information that are written using binary digits 0s and 1s.
The file processing in python is done by two different types of approaches. One is processing the content in the file. Another one is processing the directory. The first one can be done by the built in functions. The second one will be processed by the os module methods. In this article we will concentrate only on the file content manipulation.
Operations on File
The operations performed on a file is called the file operation. Following is the list of operations can be applied on a file in python.
- Opening or Creating a File
- Writing a File
- Reading a File
- Closing a File
- Renaming a File
- Deleting a File
Opening or Creating a New File in Python
The very first thing to do in file handling is the creation of file. The method open()
is used to open an existing file or creating a new file. If the complete directory is not given then the file will be created in the directory in which the python file is stored. The syntax for using open() method is given below.
Syntax:file_object = open ( file_name, “Access Mode”, Buffering )
File name is a unique name in a directory. The open() function will create the file with the specified name if it is not already exists otherwise it will open the already existing file. The open method returns file object which can be stored in the name file_object
.
The access mode is the string which tells in what mode the file should be opened for operations. There are three different access modes are available in python.
R eading: Reading mode is crated only for reading the file. The pointer will be at the beginning of the file.
Writing:Writing mode is used for overwriting the information on existing file.
Append:Append mode is same as the writing mode. Instead of over writing the information this mode append the information at the end.
Below is the list of representation of various access modes in python.
Reading ModeR - Opens a text file for Reading
Rb - Opens a binary file for Reading
r+ - Opens a text file for Reading and Writing
rb+ - Opens a binary file for Reading and WritingWriting ModeW - Opens a text file for Writing
Wb - Opens a binary file for Writing
w+ - Opens a text file for Reading and Writing
wb+ - Opens a binary file for Reading and WritingAppend ModeA - Opens a text file for appending
Ab - Opens a binary file for appending
a+ - Opens a text file for appending and reading
ab+ - Opens a binary file for appending and reading
What is Buffering ?
Buffering is the process of storing a chunk of a file in a temporary memory until the file loads completely. In python there are different values can be given. If the buffering is set to 0 , then the buffering is off. The buffering will be set to 1 when we need to buffer the file.
Creating our first file
We have discussed lot of theoretical part in the article. Let us try to create a file object in python. Before creating a file object we have to decide proper attributes to be applied. The major three things in file object creation are file name, access mode and buffering. Let the file name be my_file_name
. We are going to create a new file in the text format. We have to write something on the file. So choosing the mode for reading and writing will be perfect one. As I am going to create text based file, I can choose the mode w+
for the file. Buffering can be used for text type file. So we can enable the buffering.
my_file = open(my_file_name.txt,"w+",1)
Now a text file with the name my_file_name
is created successfully. We can able to apply various methods on the file object. Here is the list of useful methods used on file object.
file.name - Returns the name of file file.mode - Returns the access mode of the file file.closed - Returns true if the file is closed
Let us apply all the methods on our file object my_file
.
my_file = open("my_file_name.txt", "w+", 1) print(my_file.name) print(my_file.mode) print(my_file.closed)
Output
my_file_name.txt w+ False
Let us try the same with the r+
access mode instead of w+
.
my_file = open("my_file_name.txt", "r+", 1) print(my_file.name) print(my_file.mode) print(my_file.closed)
Output
Traceback (most recent call last): File "main.py", line 1, in <module> my_file = open("my_file_name.txt", "r+", 1) FileNotFoundError: [Errno 2] No such file or directory: 'my_file_name.txt'
If you need to use r+
the file must present already in the directory. Otherwise it will give some error. As we created a new file there is no information available in the text file. You can check manually by opening the file in the directory.
Writing Information in the File
In the previous step we have created a file for reading and writing modes. In this part we will write something in the text document. The write()
method is used for writing a string inside a file. The syntax for using write function is given below.
Syntax: file_object .write(“String”)
string = "This is a String in Python" my_file = open(my_file_name.txt,"w+",1)my_file.write(string)
Now the information will be written in the text file. This information will be saved once we close the file.
Reading Information in the File
The text information in the text file can be extracted with the help of read() function. The syntax for reading is given below.
Syntax:var_name = file_object .read(index)
string = "This is a String in Python" my_file = open(my_file_name.txt,"r+",1) my_file.write(string)my_string = my_file.read() print(my_string)
Output
This is a String in Python
The index argument passed inside the read()
method determines how many characters to be printed from the file.
Closing a File in Python
The previous programs are not suggested for real time. After processing the content in a file, the file must be saved and closed. To do this we can use another method close()
for closing the file. This is an important method to be remembered while handling files in python.
Syntax: file_object .close()
string = "This is a String in Python" my_file = open(my_file_name.txt,"w+",1) my_file.write(string) my_file.close() print(my_file.closed)
Output
True
The method file.closed
returns True as the file is closed.
Renaming a File
The file name can be changed by a method rename()
. The rename() method is available in the os module. Before calling the rename function we have to import the os module into our program. The syntax is given below.
Syntax: os .rename(old_name, new_name)
import os string = "This is a String in Python" my_file = open("my_file_name.txt", "w+", 1) my_file.write(string) os.rename("my_file_name.txt", "renamed.txt")
Now the file will be renamed into the new name.
Deleting a File
Another method from the same os module, remove()
is used to delete an existing file in a directory. The following is the syntax for using delete operation.
Syntax: os .remove(file_name)
import os string = "This is a String in Python" my_file = open("my_file_name.txt", "w+", 1) my_file.write(string) os.remove("my_file_name.txt")
Thank you all for reading this article. I hope this article helped you to learn something in python. Continuous practice makes better programmers. The following articles may help you.
Happy Coding!
Follow me on Medium .
以上所述就是小编给大家介绍的《Complete Guide on File Handling in Python》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
神经网络与机器学习(原书第3版)
[加] Simon Haykin / 申富饶、徐烨、郑俊、晁静 / 机械工业出版社 / 2011-3 / 79.00元
神经网络是计算智能和机器学习的重要分支,在诸多领域都取得了很大的成功。在众多神经网络著作中,影响最为广泛的是Simon Haykin的《神经网络原理》(第3版更名为《神经网络与机器学习》)。在本书中,作者结合近年来神经网络和机器学习的最新进展,从理论和实际应用出发,全面、系统地介绍了神经网络的基本模型、方法和技术,并将神经网络和机器学习有机地结合在一起。 本书不但注重对数学分析方法和理论的探......一起来看看 《神经网络与机器学习(原书第3版)》 这本书的介绍吧!