Documents for Python Programming (Part 1)

参与拿奖:本文已参与「新人创作礼」活动,一起开启掘金创作之路
复制代码
1. Text form:

According to the organization in the file, it can be divided into: ① Text file (text file stores regular strings, which consist of several lines of text, usually each line is terminated with '\n'. The string refers to the ability of Notepad or other text editor Strings that are normally displayed, edited, and can be directly read and understood by humans) ②Binary files (the object content is stored in bytes, which cannot be edited directly with Notepad or other ordinary file editors, and usually cannot be It can be read and understood directly by humans, and special software is required to read, display, modify and execute after decoding)

2. File operation format:

①File object name=open(filename,[,open method[,buffer]]) ②File name: the file to be operated, needs a relative path, you can use the original string ③Open method: read-only (r) , write-only (w), append (a), binary mode (b), read-write (+), of which binary mode and read-write can be used in combination with other modes ④File object attribute: closed (judging whether the file is closed or not , close the file without closing, return True if closed), mode (return the file open mode), name (return the open file name) #buffer: specifies the cache mode for reading and writing files, 0 (meaning no cache), 1 ( Represents cache), n (n>1, represents the size of the buffer area), the default value (the default value is the cache mode)

3. Common methods of file objects:

flush()    把缓冲区内容写入文件,但不关闭文件
close()    把缓冲区内容写进文件,并关闭文件,释放文件对象
read([size])   从文件中读取size个字符的内容作为结果返回,如果省略size则表示一次性读取所有内容
readline() 读取文本一行内的内容
readlines()    读取文本行内容,并将每一行存进一个列表中,返回该列表
seek(offset[,wehence]) 把文件指针移动到新的位置,offset表示相对于whence的位置,whence可以为0(表示从文件开头开始计算),1(表示从当前位置开始计算),2(表示从文件末开始计算)
tell() 返回文件指针当前的位置
truncate([size])   删除从当前指针位置到文件末尾的内容,如果指定了size的值,则只保留前size个字节,其余1的删除
writes(s)  把字符串内容s写进文件
writelines(s)  把字符串列表写入文本文件,不添加换行符
复制代码
4. Case use

①Open the file in append mode and write "Hello, my open file! "

#方法一,需要显示调用close()
fp1=open('1.txt','a+')
s='Open File first way!'+'\n'
fp1.write(s)
fp1.close()
#方法二,使用with关键字,会自动管理资源
s='Open file second way!'+'\n'
with open('1.txt','a+') as f:
    f.write(s)
复制代码

View text content

#rean()/readline()/readlines()
fp=open('1.txt','r+')
print('读取所有内容:',fp.read(),end='\n')
print('查看当前文件指针:',fp.tell(),end='\n')
print('设置文件指针:',fp.seek(0),end='\n')
print('读取第一个字符内容:',fp.read(1),end='\n')
print('读取第一行内容:',fp.readline(),end='\n')
print('读取所有行内容,以列表形式存储:',fp.readlines(),end='\n')
fp.close()
复制代码

②Case 2 Read all integers in the text and sort them in ascending order

import re
def order(filename):
    with open(filename,'r+') as fp2:
        s=fp2.read()
        #print(s)
    list=re.split(r'\s+',s)
    for i in range(len(list)):
        list[i]=int(list[i])
    list.sort()
    #print(list)
    #print(list)
    #print(list,end='\n')
order('2.txt')
复制代码

③Case 3 Open a file, add a line number to each line at the end, and use the list comprehension formula

def add(filename):
    with open(filename,'r+') as fp3:
        s1=fp3.readlines()
    #for i in range(len(s)):
    #    s[i]+='\n'
    s1=[s.rstrip()+' '*(100-len(s))+'#'+str(index)+'\n' for index,s in enumerate(s1)]
    with open('4.txt','a+') as fp4:
        fp4.writelines(s1)
        #for i in range(len(s)):
        #    fp4.write(s[i])
add('3.txt')
复制代码
5. Operation of binary files

1) Binary file operation, only by correctly understanding the serialization and structuring rules of binary files, can we correctly understand the content and design correct deserialization rules. Commonly used binary file serialization modules include struct, pickle, json, marshal , shelve.

2) The case uses ① pickle module to write information to the file

import pickle
fp5=open('1.dat','wb')
n=1
i=100
c=1.9
s='中国'
lis=[[1,2,3],[2,3,4],[4,5,6]]
dic={'1':'1','2':'2','3':'3'}
tup=(1,2,3,4)
coll={1,2,3,4}
try:
    pickle.dump(n,fp5)
    pickle.dump(i,fp5)
    pickle.dump(c,fp5)
    pickle.dump(dic,fp5)
    pickle.dump(lis,fp5)
    pickle.dump(tup,fp5)
    pickle.dump(coll,fp5)
    pickle.dump(s,fp5)
except:
    print('output error!')
finally:
    fp5.close()
复制代码

Read information from a file

fp6=open('1.dat','rb')
n=pickle.load(fp6)
i=0
while i<n:
    print(pickle.load(fp6),end='\n')
    i+=1
fp6.close()
复制代码

②The stuct module is written to the file

import struct
sn=struct.pack('if?',n,i,c)
fp7=open('2.dat','wb')
fp7.write(sn)
fp7.write(s.encode())
fp7.close()
复制代码

read operation

fp8=open('2.dat','rb')
sn=fp8.read(9)
tu=struct.unpack('if?',sn)
print(tu)
n,x,b=tu
print('n=',n,'x=',x,'b=',b,end='\n')
s=fp8.read(9)
s=s.decode()
print('s=',s,end='\n')
复制代码
Study Notes:

1. File type: text file (can be directly interpreted by humans); binary file (requires special tools to complete the interpretation);

2.文件打开常见操作有以读的方式(r),以写的方式(w),以二进制模式(b),以追加模式(a),以读写模式(+)

3.文件对象常用方法:

#flush()    把缓冲区内容写入文件,但不关闭文件
#close()    把缓冲区内容写进文件,并关闭文件,释放文件对象
#read([size])   从文件中读取size个字符的内容作为结果返回,如果省略size则表示一次性读取所有内容
#readline() 读取文本一行内的内容
#readlines()    读取文本行内容,并将每一行存进一个列表中,返回该列表
#seek(offset[,wehence]) 把文件指针移动到新的位置,offset表示相对于whence的位置
# ,whence可以为0(表示从文件开头开始计算),1(表示从当前位置开始计算),2(表示从文件末开始计算)
#tell() 返回文件指针当前的位置
#truncate([size])   删除从当前指针位置到文件末尾的内容,如果指定了size的值,则只保留前size个字节,其余1的删除
#writes(s)  把字符串内容s写进文件
#writelines(s)  把字符串列表写入文本文件,不添加换行符
复制代码

4.二进制文件的操作需要引用其他模块,常见的有struct、pickle、json、marshal、shelve.

5.在打开文件时,如果没有找到指定文件,会自动创建一个文件。

Guess you like

Origin juejin.im/post/7079586163832389645