打开一个文件语法如下
fileVariable = open(filename, mode)
python读写有以下常见模式
模式 | 描述 | 若文件不存在 | 是否覆盖 |
r | 读取 | 报错 | - |
r+ | 可读可写 | 报错 | 是 |
w | 只能写 | 创建 | 是 |
w+ | 可读可写 | 创建 | 是 |
a | 在文件最后写入 | 创建 | 否 |
a+ | 在文件文件最后读写 | 创建 | 否 |
比如以写入模式打开一个example.txt
input = open("example.txt", "w")
也可以用绝对路径来打开文件,如下所示
input = open(r"C:\katou\example.txt", "w")
路径前的r表明这是行字符串,python解释器会按字面意思解释反斜线,这里也可以使用转义字符\\
为防止已存在文件被覆盖,可以用os.path模块里的isfile来确认文件是否存在
import os.path
if os.path.isfile("example.txt"):
print("file already exists")
在example.txt中写入数据
def main():
#open example.txt as write mode
outfile = open("example.txt", "w")
outfile.write("CNY\n")
outfile.write("USD\n")
outfile.write("SGD")
#close example.txt
outfile.close()
main()
结束后的example.txt
CNY
USD
SGD
读取操作
python中一般有两种读取方法 read(),readline()和readlines(),read()以字符串形式读取全部文件,readline()读取当前指针到下个换行符的内容,包括\n,readlines()方法会把所有行放在一个字符串列表里
e.g.
def main():
f = open("example.txt", "r")
print("Using read:")
s = f.read()
print(s)
f.close()
f = open("example.txt", "r")
print("Using read(number):\n")
s1 = f.read(3) #read the first three characters
s2 = f.read(7)
print(s1)
print(repr(s2))
f.close()
f = open("example.txt", "r")
print("Using readline:")
line1 = f.readline()
line2 = f.readline()
line3 = f.readline()
line4 = f.readline()
print(repr(line1))
print(repr(line1))
print(repr(line1))
print(repr(line1))
f.close()
main()
'''
Using read:
CNY
USD
SGD
Using read(number):
CNY
'\nUSD\nSG'
Using readline:
'CNY\n'
'USD\n'
'SGD'
''
'''
repr()可以显示出未经转义的文本,在最后一行使用readline()会返回空字符
从文件读取所有数据
一般可以用read()读取一整个文件或者用readlines()返回一整个字符串列表,但如果储存器放不下就要逐行解决。python中也提供了for
for line in file
#process here...
(CC BY-SA 4.0)
更多推荐
python文本读取与写入
发布评论