Introduction to Python3 (11) - IO programming

1. File reading and writing

  Python's file operations are compatible with C

 1. Read a text file

 The read file operation is as follows:

f = open("F:/1.txt", "r")
data = f.read()
print(data)

  Where "r" means read, read the file, and then use the read() method to read the contents of the file

  Like Java, the operation file needs to be closed, and it is strongly recommended to close in finally, the code is as follows:

try:
    f = open("F:/1.txt", "r")
    data = f.read()
    print(data)
finally:
    if f:
        f.close()

  but! Python supports the with operation again, which is indeed much simpler than Java having to write similar code above:

with open("F:/1.txt", "r") as f:
    print(f.read())

  In this way, try finally and close can all be omitted!

  Here read() can also add the parameter size to limit the number of bytes read, preventing too much reading at one time and bursting:

print(f.read(4))

  Or read line by line is also wide:

readline() #Read a line 
readlines() #Read all lines, return list
for line in f.readlines():
    print(line.strip()) # 把末尾的'\n'删掉

  This kind of object with read() method is called file-like Object, and the common one is StringIO

  2. Read binary files

    Use rb mode to open it:

f = open("F:/1.jgp", "rb")
f.read()

  3. Character encoding

    The default is UTF-8, and the encoding parameter can be added to specify the encoding.

f = open("F:/1.txt", "r", encoding="GBK")
f.read()

     To ignore some messy errors, you can use errors :

 f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore')

  4. Write the file

    Similar to reading, w and wb write text files and binary files, and file encoding is the same as reading files.

with open("F:/1_new.txt", "w") as f:
    f.write("Hello Python3!")

    w是覆盖写的形式,追加使用a参数,完整参照文档

二、StringIO与BytesIO

  1.StringIO

    在内存中读写string,称之为StringIO。它可以在内存中进行读写:

from io import StringIO

f = StringIO()
f.write("Hello ")
f.write("Python3!")
print(f.getvalue())

    可以像文件一样进行操作:

from io import StringIO

f = StringIO("Hello\nPython3!")
while True:
    line = f.readline()
    if line == "":
        break
    print(line.strip())

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324891793&siteId=291194637