文件源代码
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):
===========================================================
Character Meaning(mode)
--------- -------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
【写】
1.1 文件创建,并写入数据(全文替换):
“”“
文件不存在时,先创建文件,再写入数据。
文件存在时,直接将文件的内容删除后,写入write的内容。
“”“
file='/Users/lyx/软件测试/python/test/testfile.txt'
with open(file,'w') as a:
a.write('这是第1行数据!')
备注:
1)直接使用open方法打开文件,结束需要使用close关闭文件,否则会占用系统资源;
2)使用with open读写文件,文件执行完毕后,自动关闭,无需使用close操作;
1.2 文件追加内容
file='/Users/lyx/软件测试/python/test/testfile.txt'
with open(file,'w') as a:
a.write('这是第1行数据!')
"""
a:在文件末尾追加内容。
"""
with open(file,'a') as a:
a.write('n')
a.write('这是第2行数据!')
【读】
2.1 使用read()读取文件内容,返回str格式的内容。
file='/Users/moon/Lyx/test/python/Tenancy/files.txt'
with open(file,'w') as f:
f.write('第1行')
f.write('n')
f.write('第2行')
with open(file,'r') as f:
c=f.read()
print(c)
print('----------------------------------------------')
print(type(c))
2.2 使用readlines()读取文件内容,返回str格式的内容。第1行
第2行
----------------------------------------------
file='/Users/moon/Lyx/test/python/Tenancy/files.txt'
with open(file,'w') as f:
f.write('第1行')
f.write('n')
f.write('第2行')
with open(file,'r') as f:
c=f.readlines()
print(c)
print('----------------------------------------------')
print(type(c))
['第1行n', '第2行']
----------------------------------------------



