一、Python文件模式
模式 | 描述 |
---|---|
r | 只读模式 |
w | 只写模式,清除路径下同名文件数据 |
x | 只写模式,创建新文件,但存在同名路径时失效 |
a | 添加到已经存在的文件,若不存在就创建 |
二、语法
1.打开文件
with工作原理:紧跟with后面的语句被求值后,返回值赋给as后面的变量;当with后面的所有代码块全部执行完成后,python会在合适的时候自动将其关闭。
with open(filename, mode, encoding) as fp:
2.读写方法
方法 | 描述 |
---|---|
read([size]) | 返回字符串,size控制读取的字节数 |
readlines([size]) | 返回文件行内容的列表 |
write(str) | 将字符串写入文件 |
writelines() | 写入列表 |
例如:
读取数据并显示
with open('file') as fp:
contents = fp.read() # 返回一个长长的字符串
print(contents)
逐行读取
with open('file') as fp:
for line in fp:
print(line.rstrip())
也可以将各行存储在列表中,再在with代码块外打印
with open('file') as fp:
lines = fp.readlines()
for line in lines:
print(line)
写入内容
with open('tmp.txt', 'w') as handle:
handle.writelines(x for x in open(path) if len(x) > 1)
with open('tmp.txt') as f:
lines = f.readlines()
3. 路径
python中正确读取路径,有3种方式:
(1)“C:/path/to/file.txt”
(2)r"C:\path\to\file.txt"
(3)“C:\path\to\file.txt”
注:在文件路径中直接使用反斜杠,将引发错误,因为反斜杠会对字符进行转义。