Python 文件操作

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Python 中的文件模式

Character Meaning
'r' open for reading (default)

'w' open for writing, truncating the file first
    If file does not exist, it creates a new file.

'x' open for exclusive creation, failing if the file already exists

'a' open for writing, appending to the end of the file if it exists
    If file does not exist, it creates a new file.

'b' binary mode

't' text mode (default)

'+' open a disk file for updating (reading and writing)

'U' universal newlines mode (deprecated)

读取文件的全部内容

open("test.txt", mode="r", encoding='utf8').read()    

逐行读文件

filepath = 'test.txt'  
with open(filepath) as fp:  
    for cnt, line in enumerate(fp):
        print("Line {}: {}".format(cnt, line))

with open(filepath) as fp:
    for line in fp:
        print(line, end='')

向文件添加文本

filepath = 'test.txt'
with open(filepath, 'a') as wf:
    wf.write("hello world!\n")

"+"的应用

filepath = 'test.txt'
with open(filepath, 'a+') as wf:
    wf.write('hello, ')
    wf.seek(0)
    wf.write('world!') # If the file is opened for appending using either 'a' or 'a+', any seek() operations will be undone at the next write
    wf.seek(0)
    content = wf.read()
    print(content)

参考:

python open


Python

这篇文章: 有用 无用
创建 2018-08-05 23:11:01 / 更新 2018-10-16 19:17:41