Home >Backend Development >Python Tutorial >File operations in Python

File operations in Python

高洛峰
高洛峰Original
2017-02-27 17:02:161345browse

1. The objects that can call methods must be objects, such as values, strings, lists, tuples, dictionaries, and even files. Everything in Python is an object.

 str1 = 'hello'
 str2 = 'world'
 str3 = ' '.join([str1,str2])
 print(str3)

2. Three basic file operation modes: r (only-read), w (only-write), a (append)

The process of operating files:

First, create a file object.

Second, call the file method to operate.

Third, don’t forget to close the file. (If the file is not closed, the content will be placed in the cache. Although Python will automatically read the content to the disk at the end, just in case, you must develop the habit of closing the file)

File file1

一张褪色的照片,
好像带给我一点点怀念。
巷尾老爷爷卖的热汤面,
味道弥漫过旧旧的后院;
流浪猫睡熟在摇晃秋千,
夕阳照了一遍他咪着眼;
那张同桌寄的明信片,
安静的躺在课桌的里面。

(1)r mode

Writing content in read-only mode will report an error.

 f = open('file1','r')
 f_read = f.read()   #read是逐字符地读取,read可以指定参数,设定需要读取多少字符,无论一个英文字母还是一个汉字都是一个字符。
 print(f_read)
 f.close()

 f = open('file1','r')
 f_read = f.readline() #readline只能读取第一行代码,原理是读取到第一个换行符就停止。
 print(f_read)
 f.close()

 f = open('file1','r')
 f_read = f.readlines() #readlines会把内容以列表的形式输出。
 print(f_read)
 f.close()

 f = open('file1','r')
 for line in f.readlines() #使用for循环可以把内容按字符串输出。
   print(line) #输出一行内容输出一个空行,一行内容一行空格... 因为文件中每行内容后面都有一个换行符,而且print()语句本身就可以换行,如果不想输出空行,就需要使用下面的语句:print(line.strip())
 f.close()

(2)w mode

All contents in the file will be cleared before operation. For example, if you write 'hello world' in file1, after the program is executed, there will be only the sentence 'hello world' in file1

 f = open('file1','w',encoding='utf8')  #由于Python3的默认编码方式是Unicode,所以在写入文件的时候需要调用utf8,以utf8的方式保存,这时pycharm(默认编码方式是utf8)才能正确读取,当读取文件时,文件是utf8格式,pycharm也是utf8,就不需要调用了。
 f_w = f.write('hello world')
 print(f_w)  #有意思的是,这里并不打印'hello world',只打印写入多少字符
 f.close()

(3)a mode

Different from w mode, a mode does not clear the original content, but moves the cursor to the last position of the content and continues to write new content. For example, append 'hello world'

 f = open('file1','a')
 f_a = f.write('hello world')
 print(f_a) #还是会打印写入的字符数
 f.close()

at the end to print the file, and append 'helloworld' after 'stray cat sleeping soundly on the swing' to output

In r mode, we said that we use for loop and readlines() to output the file content. The principle of this output content is: open the file, read the entire content into the memory, and then print the input. When the file is large , this reading method is unreliable and may even cause the machine to crash. We need to close the file in time, as follows:

f = open('file','r')
data=f.readlines()  #注意及时关闭文件
f.close()

num = 0
for i in data:
  num += 1
  if num == 5:
    i = ''.join([i.strip(),'hello world']) #不要使用“+”进行拼接
  print(i.strip())
f.close()

For big data files, use the following method:

num = 0
f.close()  #不要过早关闭文件,否则程序不能识别操作句柄f.
f = open('file','r')
for i in f:  #for内部把f变为一个迭代器,用一行取一行。
  num += 1
  if num == 5:
    i = ''.join([i.strip(),'hello world'])
  print(i.strip())
f.close()

3.tell and seek

tell: query the cursor position in the file

seek: cursor positioning

f = open('file','r')
print(f.tell())  #光标默认在起始位置
f.seek(10)    #把光标定位到第10个字符之后
print(f.tell())  #输出10
f.close()
----------------------
f = open('file','w')
print(f.tell())  #先清空内容,光标回到0位置
f.seek(10)    
print(f.tell())
f.close()
----------------------
f = open('file','a')
print(f.tell())  #光标默认在最后位置
f.write('你好 世界')
print(f.tell())  #光标向后9个字符,仍在最后位置
f.close()

4.flush synchronously transfers data from cache to disk

Example to implement progress bar function

import sys,time  #导入sys和time模块
for i in range(40):
  sys.stdout.write('*')
  sys.stdout.flush()  #flush的作用相当于照相,拍一张冲洗一张
  time.sleep(0.2)
下面代码也能够实现相同的功能
import time 
for i in range(40):
  print('*',end='',flush=True) #print中的flush参数
  time.sleep(0.2)

5.truncate truncation

Cannot be executed in r mode. In

w mode, all data has been cleared. Using truncate has no meaning. In

a mode, the content after the specified position is truncated. .

 f = open('file','a')
 f.truncate(6) #只显示6个字节的内容(6个英文字符或三个汉字),后面的内容被清空。

6. Summary of cursor position

A Chinese character has two bytes, and there are four methods involving the cursor position: read, tell, seek, truncate.

#--------------------------光标总结head-----------------------------------
f = open('file','r')
print(f.read(6)) #6个字符
print(f.tell())  #位置12字节,一个汉字两个字节
f.close()

f = open('file','r')
f.seek(6)      #6个字节
print(f.tell())
f.close()

f = open('file','a')
print(f.tell())  #光标默认在最后位置
f.write('你好 世界')
print(f.tell())  #光标向后9个字节,一个汉字两个字节,仍在最后位置 182-->191
f.close()

f = open('file','a',encoding='utf-8')
print(f.truncate(6)) #由于需要光标定位位置,所以也是字节。只显示6个字节的内容(6个英文字母或三个汉字,一个汉字两个字节),后面的内容被清空。
f.close()
#-----------------------------光标总结end---------------------------------

7. The other 3 modes: r+, w+, a+

r+: read and write mode, the cursor is at the starting position by default. When writing is needed, the cursor automatically moves to the end

w+: Write and read mode, first clear the original content, then write, you can also read

a+: Append reading mode, cursor The default is the last position, which can be written directly and can also be read.

f = open('file','a')
print(f.tell())  #末尾207位置
f.close()

f = open('file','r+')
print(f.tell())  #0位置
print(f.readline()) #读取第一行
f.write('羊小羚')   #光标移到末尾207位置并写入
print(f.tell())  #213位置
f.seek(0)     #光标移到0位置
print(f.readline())  #读取第一行
f.close()

8. Modify the file content

Idea: Due to the data storage mechanism, we can only read the contents of file 1 Come out, modify it, and put it in file 2.

f2 = open('file2','w',encoding='utf8')  #写入的时候必须加utf8
f1 = open('file','r')
num = 0
for line in f1: #迭代器
  num += 1
  if num == 5:
    line = ''.join([line.strip(),'羊小羚\n'])  #里面就是对字符串进行操作了
  f2.write(line)
f1.close()
f2.close()

9.with statement

can operate on multiple files at the same time. When the with code block is executed, the file will be automatically closed. To release memory resources, there is no need to specifically add f.close(). We will experience the usage and benefits of with through the following example.

Rewrite the code in 8 using the with statement


num = 0
with open('file','r') as f1,open('file2','w',encoding='utf8') as f2:
  for line in f1:
    num += 1
    if num == 5:
      line = ''.join([line.strip(),'羊小羚'])
    f2.write(line)

10. Summary

The above is the entire content of this article, I hope it can be helpful to everyone. If you have any questions, you can leave a message and communicate

For more articles related to file operations in Python, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn