程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python notes 20- common file reading and writing 1

編輯:Python

One 、 File read and write

Read / write classification of common files :

1. Plain text file :txt py md html doc etc.
2.csv file :.csv
3. Binary : picture , Audio , video , Compression package, etc
4. Serialization and deserialization of objects :pickle and json
5.excel file : Third party modules are required xlrd and xlwt

File reading and writing is also an object-oriented idea , Common operating systems do not allow programs to directly access the disk , You can read and write files through file descriptors

f = open(path,mode,encoding), Executing this code just opens a file object in memory ,f It's called a file descriptor , What is stored in this object is the open file object

1. Common file read / write

1.1 write in

# 1. Open file :open()
"""
Be careful :
a. have access to w or a Write content , When the specified file path does not exist , Can generate new files
b.w: Delete the original file , Generate a new file , So if the file exists , It can be understood as overwriting the contents of the source file
c.a: If the file exists, the specified content is appended to the content of the source file
"""
# f1 = open(r'file1.txt','w',encoding='utf-8')
# f1 = open(r'file2.txt','w',encoding='gbk')
# f1 = open(r'file2.txt','w',encoding='gbk')
f1 = open(r'file2.txt','a',encoding='gbk')
# 2. Write content :write()/writelines()
# a.write() *******
# f1.write("hello Hello ")
# Means refresh , If the internal capacity to be written is large , Improve write efficiency
# f1.flush()
# b
# f1.writelines("13413\nfahjghj\n Hello \n571857")
f1.writelines(['aaaa','bbbb','cccc']) # Concatenate the string elements in the list into a string , Direct write
f1.flush()
# 3. Close file :close()
f1.close()

1.2 Read

# 1. Open file :open()
"""
open(file,mode='r',encoding)
file: The file path to open , Use either a relative path or an absolute path
mode: The way the file is opened ,
'r' open for reading (default)
'w' open for writing, truncating the file first, Delete the original file , Generate a new file , Write content , If the file with the specified path does not exist , Will be created automatically
'x' create a new file and open it for writing, Create a new file , Used to write
'a' open for writing, appending to the end of the file if it exists, Append the specified content to the existing content of the existing file , You can create a new file
'b' binary mode, For operating binary files
rb: Open a binary file read-only
wb: Open a binary file by writing
'+' open a disk file for updating (reading and writing)
r+: Focus on reading
w+: Focus on writing
encoding: Coding format
utf-8/UTF-8/UTF8/utf8
gbk/GBK
"""
"""
Be careful 1:
a. When opening a file to read its contents ,encoding The coding format shall be consistent with that of the original document , Otherwise you cannot read
b. When opening a file to read its contents , The file path must exist
c. Turn on mode mode The default value is r, So read ordinary text files ,r It can be omitted
d. When starting to read content , By default, the file descriptor is at the beginning of the file , Then read according to the specified rules
e.read() It is applicable to the case that the content of the document is less ,read(size) With the help of the loop, it is applicable to the case that the contents of the file are read more
readlines() It is applicable to the case that the contents of the document are regular
f. After the file operation , Try to close the file , Avoid wasting system resources
"""
f = open(r' To oak .txt','r',encoding='gbk')
# print(f,type(f))
# 2. Read the content :read()/readline()/readlines()
# a.f.read() Default all read / write
r1 = f.read() # ******
print(r1)
# r1 = f.read(5)
# print(r1)
# r1 = f.read(5)
# print(r1)
# b.readline(): Read one line at a time
# r2 = f.readline()
# print(r2)
# c.readlines(): Read all , The return value is a list , A line is an element ******
# r3 = f.readlines()
# print(r3)
# d.readable(): It is not used to read the contents of the file , Just a tag that specifies whether the file is readable , The return result is a Boolean value
# r4 = f.readable()
# print(r4)
# 3. Close file :close()
f.close()

1.3 Cyclic operation

# 1. demand : You can only read at one time 5 Characters
# read(n)
import os
path = r"file1.txt"
f = open(path,"r",encoding="utf-8")
# Count the number of characters in the file
total_size = os.path.getsize(path)
# Set the number of characters to be read at a time , In general , The number of characters read at a time is set to 2 To the power of
sub_size = 1024
while total_size > 0:
r = f.read(sub_size)
print(r)
total_size -= sub_size
f.close()
# 2. demand : Read one line at a time , Read everything
# readline()
path = r"file1.txt"
f = open(path,"r",encoding="utf-8")
r = f.readline()
print(r)
while r:
r = f.readline()
print(r)
f.close()

1.4with Context

"""
adopt with Read / write files in context
grammar :
with open() as f:
Read / write in
explain :f It's actually a variable , Represents the open file object
Be careful : If you use with Context , Whether read or write , Finally, there is no need to close the file manually
When with Code block execution complete , The files involved will be automatically closed
"""
# 1. Read
with open(r' To oak .txt','r',encoding='gbk') as f:
r = f.read()
print(r)
# 2. write in
with open(r"file1.txt",'w',encoding='utf-8') as f:
f.write('abc Computer ')
f.flush()

2. Binary reading and writing

# Common binary files are : picture , Audio and video , Compression package, etc
"""
Be careful :
a. If you want to manipulate binary files , Then use rb or wb To open binary files
b. If the rb or wb To open binary files , Then there is no need to specify encoding
"""
# 1. Read
with open(r"111.png",'rb') as f1:
r = f1.read()
print(r)
# 2. write in
with open(r"img.png",'wb') as f2:
f2.write(r)
f2.flush()

3.CSV File read and write

CSV(Comma Separated Values Comma separated values )

.csv It's a file format ( Such as .txt、.doc etc. ), It's understandable .csv A file is a kind of pure text file with a special format . It's a sequence of characters , Use commas or tabs of English characters between characters (Tab) Separate

therefore ,CSV The file itself is a plain text file , This file format is often used as a format for data interaction between different programs

stay windows On the system environment .csv There are many ways to open files , Like Notepad 、excel、Notepad++ etc. , As long as it is a text editor, it can open correctly

3.1 Read

"""
csv Why files are often used :
a. It can be used as an intermediary for data exchange between different programs
b.Python Built in csv modular , You can use... By importing directly
c.csv Documents can be passed through excel open , If you do it directly excel, Third party modules need to be installed
"""
import csv
# from collections import Iterator
# 1. Using the reading method of normal text file, you can read csv file , however , There is no such thing as csv Characteristics of data
# with open(r'c1.csv','r',encoding='utf-8') as f:
# r = f.read()
# print(r)
# 2. Use csv Unique way to read
# a. open
with open(r'c1.csv','r',encoding='utf-8') as f:
# b. Read
# csv.reader(iterable), File object f Is itself a iterable, Return to one iterator
# Iterators have the characteristics of generators , The element is generated during the access process
r = csv.reader(f)
# print(r)
# print(isinstance(r,Iterator)) # True
# c. Ergodic iterator
datalist = []
for row in r:
# print(row)
datalist.append(row)
print(datalist)

3.2 write in

import csv
# 1. open
with open(f"c2.csv",'w',encoding='utf-8') as f:
# 2. Convert the file object to an iteratable object
csv_writer = csv.writer(f)
# 3. write in
# a. character string
# csv_writer.writerow('hello') # h,e,l,l,o
# b. list
infolist = [['name', 'age', 'hobby', 'address'], ['aaa', '10', 'dance', 'xian'], ['zhangsan', '20', 'sing', 'shanghai'], ['bbb', '14', 'piano', 'guangzhou']]
# Mode one
# for row in infolist:
# csv_writer.writerow(row)
# Mode two
csv_writer.writerows(infolist)
# 2
with open(f"c3.csv", 'w', encoding='utf-8') as f:
# c. Dictionaries
data_list = [
{'name':' Zhang San ','age':18},
{'name': ' Zhang San 2', 'age': 17},
{'name': ' Zhang San 3', 'age': 10},
{'name': ' Zhang San 4', 'age': 13}
]
csv_writer = csv.DictWriter(f,data_list[0].keys())
# Write the title , In the dictionary key Will automatically be treated as csv The title of the file is written to
csv_writer.writeheader()
# Write the text
csv_writer.writerows(data_list)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved