Python file operations

Source: Internet
Author: User

Tag: Package parameter does not require truncate type command script cannot

An introduction

The computer system is divided into three parts: the hardware, the operating system and the application.

Applications that we write in Python or other languages need to be saved on the hard drive if we want to keep the data permanently, which involves the application operating hardware, and it is well known that the application is not able to manipulate the hardware directly. The operating system encapsulates complex hardware operations into a simple interface for use by the user/application, where the file is the operating system provided to the application to manipulate the virtual concept of the hard disk, and the user or application can save its own data permanently by manipulating the file.

With the concept of a file, we no longer have to consider the details of the operation of the hard disk, just the process of manipulating the files:

#1. 打开文件,得到文件句柄并赋值给一个变量
#2. 通过句柄对文件进行操作
#3. 关闭文件

Two in Python

#1. 打开文件,得到文件句柄并赋值给一个变量
f=open(‘a.txt‘,‘r‘,encoding=‘utf-8‘) #默认打开模式就为r

#2. 通过句柄对文件进行操作
data=f.read()

#3. 关闭文件
f.close()

Process Analysis of Tri-f=open (' A.txt ', ' R ')

#1、由应用程序向操作系统发起系统调用open(...)

#2、操作系统打开该文件,并返回一个文件句柄给应用程序

#3、应用程序将文件句柄赋值给变量f

Four emphasis!!!

#强调第一点:
打开一个文件包含两部分资源:操作系统级打开的文件+应用程序的变量。在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:
1、f.close() #回收操作系统级打开的文件
2、del f #回收应用程序级的变量

其中del f一定要发生在f.close()之后,否则就会导致操作系统打开的文件还没有关闭,白白占用资源,
而python自动的垃圾回收机制决定了我们无需考虑del f,这就要求我们,在操作完毕文件后,一定要记住f.close()

虽然我这么说,但是很多同学还是会很不要脸地忘记f.close(),对于这些不长脑子的同学,我们推荐傻瓜式操作方式:
使用with关键字来帮我们管理上下文
with open(‘a.txt‘,‘w‘) as f:
   pass

with open(‘a.txt‘,‘r‘) as read_f,open(‘b.txt‘,‘w‘) as write_f:
   data=read_f.read()
   write_f.write(data)

强调第一点:资源回收

#强调第二点:
f=open(...)是由操作系统打开文件,那么如果我们没有为open指定编码,
那么打开文件的默认编码很明显是操作系统说了算了,操作系统会用自己的默认编码
去打开文件,在windows下是gbk,在linux下是utf-8。
这就用到了上节课讲的字符编码的知识:若要保证不乱码,文件以什么方式存的,
就要以什么方式打开。

f=open(‘a.txt‘,‘r‘,encoding=‘utf-8‘)

Five modes of open files

File handle = open (' File path ', ' mode ')

#1. 打开文件的模式有(默认为文本模式):
r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
w,只写模式【不可读;不存在则创建;存在则清空内容】
a, 之追加写模式【不可读;不存在则创建;存在则只追加内容】

#2. 对于非文本文件,我们只能使用b模式,"b"表示以字节的方式操作
(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、
图片文件的jgp格式、视频文件的avi格式)
rb 
wb
ab
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,
不能指定编码

#3. 了解部分
"+" 表示可以同时读写某个文件
r+, 读写【可读,可写】
w+,写读【可读,可写】
a+, 写读【可读,可写】


x, 只写模式【不可读;不存在则创建,存在则报错】
x+ ,写读【可读,可写】
xb

Six ways to manipulate files
#掌握
f.read() #读取所有内容,光标移动到文件末尾
f.readline() #读取一行内容,光标移动到第二行首部
f.readlines() #读取每一行内容,存放于列表中

f.write(‘1111\n222\n‘) #针对文本模式的写,需要自己写换行符
f.write(‘1111\n222\n‘.encode(‘utf-8‘)) #针对b模式的写,需要自己写换行符
f.writelines([‘333\n‘,‘444\n‘]) #文件模式
f.writelines([bytes(‘333\n‘,encoding=‘utf-8‘),‘444\n‘.encode(‘utf-8‘)]) #b模式

#了解
f.readable() #文件是否可读
f.writable() #文件是否可读
f.closed #文件是否关闭
f.encoding #如果文件打开模式为b,则没有该属性
f.flush() #立刻将文件内容从内存刷到硬盘
f.name

Practice, using B-mode, write a CP tool that requires the following:

1. Can copy text and copy video, pictures and other files

2. Once the user parameter is wrong, print the correct use method of the command, such as USAGE:CP source_file target_file

Tip: You can use import sys and then use SYS.ARGV to get the arguments followed by the script

import sys
if len(sys.argv) != 3:
   print(‘usage: cp source_file target_file‘)
   sys.exit()

source_file,target_file=sys.argv[1],sys.argv[2]
with open(source_file,‘rb‘) as read_f,open(target_file,‘wb‘) as write_f:
   for line in read_f:
       write_f.write(line)

Seven cursor movement within the file

1:read (3):

A. When the file is opened in text mode, the delegate reads 3 characters

B. When the file is opened in B mode, it represents a read of 3 bytes

2:tell () returns the current location of the file

3: The rest of the files within the cursor movement are in bytes such as Seek,tell,truncate

Attention:

A. Seek has three modes of movement 0,1,2, of which 1 and 2 must be performed in B mode, but whichever mode is moved in bytes, common seek (0) moves to the beginning and seek (0, 2) moves to the last face.

B. Truncate is a truncated file, so the file must be opened in a way that can be written, but not open with W or w+, because that will directly empty the file, so truncate to r+ or a or a + and other modes to test the effect

Eight changes to the file

File data is stored on the hard disk, so there is only coverage, there is no modification so to speak, we usually see the modified files, are simulated out of the effect, specifically, there are two ways to achieve:

Mode one: The contents of the file stored in the hard disk are loaded into memory, can be modified in memory, and then overwritten by memory to the hard disk (word,vim,nodpad++ and other editors).

import os

with open(‘a.txt‘) as read_f,open(‘.a.txt.swap‘,‘w‘) as write_f:
   data=read_f.read() #全部读入内存,如果文件很大,会很卡
   data=data.replace(‘alex‘,‘SB‘) #在内存中完成修改

   write_f.write(data) #一次性写入新文件

os.remove(‘a.txt‘)
os.rename(‘.a.txt.swap‘,‘a.txt‘)

Mode two: The contents of the file stored on the hard disk are read into memory line by line, the modification is completed to write a new file, and finally overwrite the source file with a new file

import os

with open(‘a.txt‘) as read_f,open(‘.a.txt.swap‘,‘w‘) as write_f:
   for line in read_f:
       line=line.replace(‘alex‘,‘SB‘)
       write_f.write(line)

os.remove(‘a.txt‘)
os.rename(‘.a.txt.swap‘,‘a.txt‘)

Python file operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.