Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python file I/O


May 10, 2021 Python2


Table of contents


Python file I/O

This chapter deals only with all the basic I/O functions, and for more functions, refer to the Python standard documentation.

Print to the screen

The easiest way to output is with a print statement, to which you can pass zero or more expressions separated by commas. This function converts the expression you pass into a string expression and writes the result to the standard output as follows:

#!/usr/bin/python
 
print "Python is really a great language,", "isn't it?";

Your standard screen will produce the following results:

Python is really a great language, isn't it?

Read keyboard input

Python provides two built-in functions to read a line of text from a standard input, the default of which is the keyboard. As follows:

  • raw_input
  • input

raw_input function

raw_input ('prompt') function reads a line from the standard input and returns a string (remove the line break at the end):

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
 
str = raw_input("请输入:");
print "你输入的内容是: ", str

This prompts you to enter any string and then display the same string on the screen. W hen I typed "Hello Python! ", its output is as follows:

请输入:Hello Python!
你输入的内容是:  Hello Python!

Input function

The input function and the raw_input function are basically interchangeable, but input assumes that your input is a valid Python expression and returns the result of the operation.

#!/usr/bin/python
 
str = input("Enter your input: ");
print "Received input is : ", str

This results in the following corresponding input:

Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is :  [10, 20, 30, 40]

Open and close files

By now, you've been able to read and write to standard inputs and outputs. Now, let's see how to read and write the actual data file.

Python provides the necessary functions and methods for basic file operations by default. You can do most of the file operations with the file object.

Open function

You must open a file with Python's built-in open() function, create a file object, and the relevant secondary method can call it for reading and writing.

Grammar:

file object = open(file_name [, access_mode][, buffering])

The details of each parameter are as follows:

  • file_name: file_name variable is a string value that contains the name of the file you want to access.
  • access_mode:access_mode determines the mode of opening the file: read-only, write-only, appended, etc. A ll desirable values can be found in the full list below. This parameter is non-mandatory and the default file access mode is read-only (r).
  • Buffering: If the value of buffering is set to 0, there will be no storage. I f the value of buffering is taken 1, the rows are stored when the file is accessed. I f you set the value of buffering to an integer greater than 1, it indicates the buffer size of the storage area. If you take a negative value, the buffer size of the register is the system default.

A full list of files opened in different modes:

Mode Describe
R Open the file as read-only. T he pointer to the file will be placed at the beginning of the file. This is the default mode.
Rb Open a file in binary format for read-only use. T he file pointer is placed at the beginning of the file. This is the default mode.
r+ Open a file for reading and writing. The file pointer is placed at the beginning of the file.
rb+ Open a file in binary format for reading and writing. The file pointer is placed at the beginning of the file.
W Opening a file is for writing only. I f the file already exists, overwrite it. If the file does not exist, create a new file.
wb Opening a file in binary format is only used for writing. I f the file already exists, overwrite it. If the file does not exist, create a new file.
w+ Open a file for reading and writing. I f the file already exists, overwrite it. If the file does not exist, create a new file.
wb+ Open a file in binary format for reading and writing. I f the file already exists, overwrite it. If the file does not exist, create a new file.
A Open a file for appending. I f the file already exists, the file pointer is placed at the end of the file. T hat is, the new content will be written after the existing content. If the file does not exist, create a new file to write to.
Ab Open a file in binary format for appending. I f the file already exists, the file pointer is placed at the end of the file. T hat is, the new content will be written after the existing content. If the file does not exist, create a new file to write to.
a+ Open a file for reading and writing. I f the file already exists, the file pointer is placed at the end of the file. T he file opens in append mode. If the file does not exist, create a new file for reading and writing.
ab+ Open a file in binary format for appending. I f the file already exists, the file pointer is placed at the end of the file. If the file does not exist, create a new file for reading and writing.

The following diagram provides a good summary of these patterns:

Python file I/O

Mode R r+ W w+ A a+
Read + + + +
Write + + + + +
Create + + + +
Covered + +
The pointer is at the beginning + + + +
The pointer is at the end + +


The property of the File object

After a file is opened, you have a file object and you can get all kinds of information about the file.

The following is a list of all the properties associated with the file object:

Property Describe
file.closed True if the file has been closed, otherwise false is returned.
file.mode Returns access mode for the open file.
file.name Returns the name of the file.
file.softspace False is returned if a space character must be followed after the print output. Otherwise, true is returned.

Here's an example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 打开一个文件
fo = open("foo.txt", "wb")
print "文件名: ", fo.name
print "是否已关闭 : ", fo.closed
print "访问模式 : ", fo.mode
print "末尾是否强制加空格 : ", fo.softspace

The above example output results:

文件名:  foo.txt
是否已关闭 :  False
访问模式 :  wb
末尾是否强制加空格 :  0

Close() method

The Close() method of the File object refreshes any information in the buffer that has not been written and closes the file, after which it cannot be written again.

When a reference to one file object is re-assigned to another file, Python closes the previous file. It is a good habit to close files using the close() method.

Grammar:

fileObject.close();

Example:

#coding=utf-8
#!/usr/bin/python
 
# 打开一个文件
fo = open("foo.txt", "wb")
print "文件名: ", fo.name
 
# 关闭打开的文件
fo.close()

The above example output results:

文件名:  foo.txt

Read and write files:

File objects provide a range of methods to make our file access easier. Let's see how to use read() and write() methods to read and write files.

The write() method

The write() method writes any string to an open file. It is important to note that Python strings can be binary data, not just text.

The write() method does not add a line break at the end of the string:

Grammar:

fileObject.write(string);

Here, the passed argument is to be written to the contents of the open file.

Example:

#coding=utf-8
#!/usr/bin/python
 
# 打开一个文件
fo = open("/tmp/foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
 
# 关闭打开的文件
fo.close()#!/usr/bin/python

The above method creates a foo .txt file, writes the received content to the file, and eventually closes the file. If you open this file, you'll see the following:

Python is a great language.
Yeah its great!!

Read() method

The read() method reads a string from an open file. It is important to note that Python strings can be binary data, not just text.

Grammar:

fileObject.read([count]);

Here, the passed argument is the count of bytes to read from the open file. The method reads from the beginning of the file, and if it does not pass in count, it tries to read as much as possible, most likely until the end of the file.

Example:

Just use the file foo we created .txt.

#coding=utf-8
#!/usr/bin/python
 
# 打开一个文件
fo = open("/tmp/foo.txt", "r+")
str = fo.read(10);
print "读取的字符串是: ", str
# 关闭打开的文件
fo.close()

The above example output results:

读取的字符串是:  Python is

File location:

The tell() method tells you the current location within the file;

The seek method changes the location of the current file. T he Offset variable represents the number of bytes to move. The From variable specifies the reference location where to start moving bytes.

If from is set to 0, this means that the beginning of the file is used as a reference location for moving bytes. I f set to 1, the current position is used as the reference location. If it is set to 2, the end of the file will be used as the reference location.

Example:

Just use the file foo we created .txt.

#coding=utf-8
#!/usr/bin/python
 
# 打开一个文件
fo = open("/tmp/foo.txt", "r+")
str = fo.read(10);
print "读取的字符串是: ", str
 
# 查找当前位置
position = fo.tell();
print "当前文件位置: ", position
 
# 把指针再次重新定位到文件开头
position = fo.seek(0, 0);
str = fo.read(10);
print "重新读取字符串: ", str
# 关闭打开的文件
fo.close()

The above example output results:

读取的字符串是:  Python is
当前文件位置:  10
重新读取字符串:  Python is

Rename and delete files

Python's os module provides ways to help you perform file processing operations, such as renaming and deleting files.

To use this module, you must import it first, and then you can call the various related functions.

Rename() method:

The rename() method requires two parameters, the current file name, and the new file name.

Grammar:

os.rename(current_file_name, new_file_name)

Example:

The following example renames an existing file test1 .txt.

#coding=utf-8
#!/usr/bin/python
import os
 
# 重命名文件test1.txt到test2.txt。
os.rename( "test1.txt", "test2.txt" )

Remove() method

You can delete files using the remove() method and need to provide the file name to delete as an argument.

Grammar:

os.remove(file_name)

Example:

The following example deletes an existing file test2 .txt.

#coding=utf-8
#!/usr/bin/python
import os
 
# 删除一个已经存在的文件test2.txt
os.remove("text2.txt")

Directory in Python:

All files are contained in different directories, but Python is easy to work with. The os module has many ways to help you create, delete, and change directories.

mkdir() method

You can use the mkdir() method of the os module to create new directories in the current directory. You need to provide a parameter that contains the name of the directory you want to create.

Grammar:

os.mkdir("newdir")

Example:

The following example creates a new directory test under the current directory.

#coding=utf-8
#!/usr/bin/python
import os
 
# 创建目录test
os.mkdir("test")

chdir() method

You can change the current directory using the chdir() method. One of the parameters required by the chdir() method is the directory name that you want to make into the current directory.

Grammar:

os.chdir("newdir")

Example:

The following example goes to the "/home/newdir" directory.

#coding=utf-8
#!/usr/bin/python
import os
 
# 将当前目录改为"/home/newdir"
os.chdir("/home/newdir")

Getcwd() method:

The getcwd() method displays the current working directory.

Grammar:

os.getcwd()

Example:

The following example gives the current directory:

#coding=utf-8
#!/usr/bin/python
import os
 
# 给出当前的目录
os.getcwd()

rmdir() method

The rmdir() method deletes the directory, and the directory name is passed by parameters.

All of this directory should be cleared before it can be deleted.

Grammar:

os.rmdir('dirname')

Example:

The following is an example of removing the "/tmp/test" directory. The name of the directory's full compliance must be given, otherwise the directory will be searched under the current directory.

#coding=utf-8
#!/usr/bin/python
import os
 
# 删除”/tmp/test”目录
os.rmdir( "/tmp/test"  )

File, directory-related methods

Three important method sources provide extensive and useful processing and manipulation of files and directories on Windows and Unix operating systems, as follows:

  • File object method: The file object provides a series of ways to manipulate files.
  • OS object methods: provides a series of methods for working with files and directories.