Python Programming - file read and write operations (with statement)

Compared with the previous statement is read and write files, can help us to automatically call close () method to avoid waste of resources of the system.

First, read and write text files

1, to write the contents of the text:

The syntax is as follows:

with open (“1.txt” , “w” , encoding = “UTF-8”) as f:

f.write("… …")

#向1.txt文件中写入文本
with open ("1.txt","w",encoding="UTF-8") as f:
    f.write("123\n")
    f.write("i love you\n")
    f.write("中国!")
2. Read the contents of the file

Syntax is as follows: The default is read
with Open ( "1.txt", encoding = "UTF-. 8") AS F:
reached, f.read ()
f.readline ()
f.readlines ()

  • read (): the entire contents of the file is read, the reading of a string type;
  • read (n): In this reading n characters;
  • readline (): according to the contents of the file is read row, read a string type, and the readline () The default line feed;
  • readlines (): the entire contents of the file is read, the reading of a list type, the behavior of each one of the elements in the list;
#read()方式读取文件
with open("1.txt",encoding='utf-8')as f:
    txt=f.read()
    print(txt)
    print(type(txt))
print('===============================')
 
#readline()方式读取文件
with open("1.txt",encoding='utf-8')as f:
    while 1:
        #readline()默认换行
        txt=f.readline()
        if txt:
            print(txt,end='')
        else:
            break
    print(type(txt))
print('===============================')
 
#readlines()方式读取文件
with open("1.txt", encoding='utf-8')as f:
     # readlines()读取的是个列表,每行为一个列表元素
     txt = f.readlines()
     print(txt)
     print(type(txt))


结果如下:
123
i love you
中国!
<class 'str'>
===============================
123
i love you
中国!<class 'str'>
===============================
['123\n', 'i love you\n', '中国!']
<class 'list'>

Second, reading and writing binary files

Such as video, audio, pictures, etc. need a bit to read and write.

1, read the information:
with open("1.jpg",'rb')as f:
    t=f.read(3)
    print(t,type(t))
 
 
结果如下:
b'\xff\xd8\xff' <class 'bytes'>
2, write information:

Referring to a specific example in Example 3

with open ('2.jpg','wb')as f:
    f.write(t)
3, read before write -> Copy:

The following example: copy a picture 1.jpg, 2.jpg to go;

#先读在写———即所谓的,复制粘贴
with open("1.jpg",'rb')as f:
    t=f.read()
    print(type(t))
 
with open ('2.jpg','wb')as f:
    f.write(t)

Guess you like

Origin blog.csdn.net/weixin_45116657/article/details/91825884