当前位置:网站首页>File and directory operations (5)

File and directory operations (5)

2022-07-28 15:37:00 WHJ226

Catalog

1. establish , Open and write files

2. Directory operation


1. establish , Open and write files

To open a file, you usually use with sentence .

After opening the file , Close it in time . If you forget to close , May bring unexpected problems . To avoid problems , Need to use with Statement instead of open() Method .

The general syntax format is as follows :

with open(filename, mode='r') as f:
    f.write(string)
mode Parameter value and description of
Parameter values explain remarks
r Open the file in read-only mode . The file must exist .
rb Open the file in binary format , And in read-only mode . Such as images 、 Voice etc. .
r+ After opening the file , You can read the contents of the file and write new contents and overwrite the original contents .
rb+ Open the file in binary format , And adopt read-write mode .
w Open the file in read-only mode . If the file exists , Then cover it ; otherwise , Create a new file .
wb Open the file in binary format , And in read-only mode . Such as images 、 Voice etc. .
w+ After opening the file , Empty the original content first , Make it an empty file , Have read and write access to this empty file .
wb+ Open the file in binary format , And use read-write mode .

for example :

string = ' open douban file '
with open('douban.txt', mode='r+',encoding='utf-8') as f: # Will open the douban File is written to douban.txt,encoding='utf-8' Specify the encoding method for 
    f.write(string) # write file 
with open('douban.txt', mode='r',encoding='utf-8') as a:
    print(a.read()) # Read the file 

The operation results are as follows :

 open douban file  # This content is written douban.txt The content in .

2. Directory operation

stay python in , When specifying the file path , You need to match the path separator \ Transference , About... In the path \ Replace with \\. for example : For relative paths "demo\m.txt" Need to use "demo\\m.txt" Instead of . in addition , You can also use the path separator \ use / Instead of .

for example :

string = ' open douban file '
path = 'E:/PYTHON/CSDN/csdn/' # Specify the path 
with open(path + 'douban.txt', mode='r+',encoding='utf-8') as f: # Will open the douban File is written to douban.txt,encoding='utf-8' Specify the encoding method for 
    f.write(string) # write file 
with open(path + 'douban.txt', mode='r',encoding='utf-8') as a:
    print(a.read()) # Read the file 

The operation results are as follows :

 open douban file  # This content is written douban.txt The content in .

原网站

版权声明
本文为[WHJ226]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/209/202207281432476368.html