Python3 for file operations

Computer files

In the computer system, the information carrier is stored to the hard disk on the computer set is called a file. Files can be of various types of text documents, images, sounds, and other programs. Often the file read and write operation when the program, from the perspective of the programmer of the file can be understood as a continuous sequence of bytes required to transmit data byte stream, the byte stream may be a single byte or large block data. File types are usually divided into text files and binary files.

File Operations

The file operations are divided into three steps in Python, first to open the file, then the file read and write operations, and finally need to close the file.

Open the file --- open function

You must use Python's built-in open () function to open a file, create a file object associated method can invoke it to read and write.

grammar:

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

Details of the various parameters is as follows:

file_name: file_name variable is a string value containing the name of the file you want to access.
access_mode: access_mode decided to open the file mode: Read, Write, and additions. See a complete list of all possible values as follows. This parameter is not mandatory, the default file is read-only access mode (r).

buffering: If the value of buffering is set to 0, there will be storage. If the value of buffering take 1, the line will register to access the file. If the value is an integer greater than 1 of buffering, indicating that this is the buffer size of the storage area. If negative, the buffer size for the system default parking zone.

Open the complete list of the different modes of file:

Python3 for file operations
Python3 for file operations

Mode is as follows:

Python3 for file operations
Python3 for file operations

File object properties

After a file is opened, you have a file object, you can get various information about the file.
The following is a list of all the properties and file objects related to:

Python3 for file operations

Close the file --- close () method

File 对象的 close()方法刷新缓冲区里任何还没写入的信息,并关闭该文件,这之后便不能再进行写入。
当一个文件对象的引用被重新指定给另一个文件时,Python 会关闭之前的文件。用 close()方法关闭文件是一个很好的习惯。
语法:
fileObject.close()

例子:

f = open('练习.txt','w',encoding='utf-8') #写文件
...
f.close()
f = open('练习.txt','r',encoding='utf-8') #读文件
...
f.close()

向文件写数据--- write()方法

write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。
write()方法不会在字符串的结尾添加换行符('\n'):
语法:
fileObject.write(string)

例子:

f = open('练习1.txt','w',encoding='utf-8')
f.write("我是中国人\n")
f.write("我爱自己的祖国\n")
f.write("我爱北京天安门\n")

输出结果:
Python3 for file operations

从文件读数据

file.read()方法从一个打开的文件中读取一个字符串。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。
语法:
file.read([count])

例子:

原文件(练习.txt)

Python3 for file operations

读文件代码如下:
f = open('练习.txt','r',encoding='utf-8')
print(f.read(1))
print(f.read(10))

输出结果:
Python3 for file operations
Python3 for file operations

使用file.readline()可以读取一行数据,同样是返回一个字符串

例子:
f = open('练习.txt','r',encoding='utf-8')
print(f.readline())

输出结果:
Python3 for file operations

file.readline()括号里面加数字,表示读取字符串个数
例子:
f = open('练习.txt','r',encoding='utf-8')
print(f.readline(1))

输出结果:
Python3 for file operations

file.readlines剩余行数据,返回的是一个字符串列表。

例子:
f = open('练习.txt','r',encoding='utf-8')
print(f.readlines())

输出结果如下:
Python3 for file operations

file.readlines()括号里面加数字,表示读取字符串个数,还有当前行剩余的也读出来

例子:
f = open('练习.txt','r',encoding='utf-8')
print(f.readlines(1)) #表示打印第一个字符串所在的那一行

输出结果如下:
Python3 for file operations

例子:
f = open('练习.txt','r',encoding='utf-8')
print(f.readlines(7)) #表示打印第7个字符串所在的那一行及前面的所有行

输出结果如下:

Python3 for file operations

注意:read()读取的方式是读取所有数据,放到内存中,这样很占内存,而且效率低小,这里推荐文件迭代器

文件迭代器

从 Python2.2开始,引进了迭代器和文件迭代,使文件操作更加高效,不需
调用 read()方法。简单说,迭代就是在for循环中读取每一行数据,示例代码如下:

f = open('练习.txt','r',encoding='utf-8')
for line in f.readlines():

 print(line.strip())

输出结果:
Python3 for file operations

注意事项:

以写方式打开文件时,不支持读操作。但是还有其他几种模式存在,使用 r+、w+、或a+ 方式打开文件,可以同时进行读写操作。
r+ 表示不清除原文件内容,读写方式打开,而新添加的数据在文件尾部
w+ 表示清除原文件内容,写读方式打开,读不到原文件的内容。
a+表示把文件指针移到文件末尾,在文件末尾可以继续写数据,读数据不受影响。

文件定位(文件指针)

tell()方法告诉你文件内的当前位置, 换句话说,下一次的读写会发生在文件开头这么多字节之后。

seek(offset [,from])方法改变当前文件的位置。
Offset变量表示要移动的字节数。
From变量指定开始移动字节的参考位置。

如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。如果设为1,则使用当前的位置作为参考位置。如果它被设为2,那么该文件的末尾将作为参考位置。

例子:

f = open('练习.txt','r',encoding='utf-8')
print(f.readline()) #打印的一行
f.seek(0) #指针返回原点
print(f.tell()) #获取当前指针位置
print(f.readline()) #再打印一行

输出结果如下:
Python3 for file operations

修改文件

1.把文件都加载到内存里面,在修改,如vim修改文件
备注:这种方式会覆盖掉原文件,而且不适合修改大文件,太消耗系统内存了,不推荐!

2.读取原文件,在修改相应文件,生成到新文件中。(推荐使用)

例子:
f = open('练习.txt','r',encoding='utf-8')
f_new =open('练习2.txt','w',encoding='utf-8')
for line in f:

if "宋代:孙洙" in line:

line = line.replace ( "Song: Sun-soo," "Song: poet")
f_new.write (Line)
f.close ()
f_new.close ()

Output:
Python3 for file operations

with use

There are some tasks, you may need to set in advance, and afterwards do the cleanup work. For this scenario, Python with statement provides a very convenient approach. A good example is the file handle, you need to obtain a file handle to read data from the file, and then close the file handle.

example:

with open('练习.txt', 'r', encoding='utf-8') as f:

for line in f.readlines():

print(line.strip())

Output:
Python3 for file operations

Built-in file object methods:

file object using open function to create, the following table lists the file objects commonly used functions:
Python3 for file operations
Python3 for file operations

Guess you like

Origin blog.51cto.com/13760351/2442274