本文为原创文章,未经本人允许,禁止转载。转载请注明出处。
1.写txt文件
1
2
3
f=open("temp.txt","w")
f.write("hello world")
f.close
"w"执行写操作。上述程序会在相应目录下生成一个temp.txt的文件,文件内容为“hello world”。
以下程序可实现自动关闭文档的操作,省去f.close():
1
2
with open("temp.txt","w") as f: #冒号不能少
f.write("hello\nworld")
\n为转义序列,表示换行。
2.读txt文件
python中有三种读取txt文件的方法:
.read().readline().readlines()
若文本temp.txt中的内容为:
1
2
hello
world
分别用三种方式去读其中的内容。
2.1..read()
.read()每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。
使用.read()读文件中的内容:
1
2
with open("temp.txt","r") as f:
print(f.read())
"r"是“只读”操作,上述程序输出为:
1
2
hello
world
其中,
f.read(0)输出为空字符。-
f.read(1)输出第1个字符,即:1
h
-
f.read(6)输出前6个字符,其中第6个字符为换行符,即:1
hello
-
f.read(7)输出前7个字符,即:1 2
hello w
-
f.read(15)输出的字符个数超过了文件所含的字符个数,并不会报错,会输出该文件的所有字符,即:1 2
hello world
2.2..readline()
.readline()每次只读取一行,通常比.readlines()慢很多。仅当没有足够内存可以一次性读取整个文件时,才应该使用.readline()。返回值也是一个字符串变量。
1
2
with open("temp.txt","r") as f:
print(f.readline())
输出为:
1
hello
其中,
f.readline(0)输出为空字符。f.readline(1)输出为h。f.readline(6)输出为hello。f.readline(7)输出为hello。
上面第3、4个例子可以看出,.readline()相当于只读了第一行hello,没有读入第二行world。
2.3..readlines()
.readlines()一次性读取整个文件,像.read()一样。🤜.readlines()自动将文件内容分析成一个行的列表🤛。用for…in…处理,返回的是一个列表结构。
1
2
with open("temp.txt","r") as f:
print(f.readlines())
输出为:['hello\n', 'world']。
f.readlines(0)输出为['hello\n', 'world']。f.readlines(1)输出为['hello\n']。f.readlines(5)输出为['hello\n']。f.readlines(6)输出为['hello\n', 'world']。
2.4.三种读取方式的比较
👉.read()
1
2
3
with open("temp.txt","r") as f:
for n in f.read():
print(n)
输出为:

👉.readline()
1
2
3
with open("temp.txt","r") as f:
for n in f.readline():
print(n)
输出为:

👉.readlines()
1
2
3
with open("temp.txt","r") as f:
for n in f.readlines():#for n in f: 也可以
print(n)
输出为:

hello和world中间多了一个空行,这是.readlines()的特性,可以通过.strip()来删除空行:
1
2
3
with open("temp.txt","r") as f:
for n in f:
print(n.strip())
输出为:

2.4.1..strip()
str.strip([char]):返回移除字符串头尾指定字符后生成的新字符串。
❗️必须针对字符串进行操作。
👉例子1:
1
2
str="000 s0t0r 0"
print(str.strip('0'))
输出的字符串为:(空格)(空格)s0t0r(空格)。去掉了首尾的0,但是会保留首尾的空格,也会保留中间部分的0。
👉例子2:
1
2
str=" s0t0r "
print(str.strip())
输出的字符串为:s0t0r,去除了首尾的空格。
👉例子3:
1
2
3
4
5
str1="aabbccdd"
print(str1.strip('a'))#输出为:bbccdd
str2="aabbccddaaa"
print(str2.strip('a'))#输出为:bbccdd
print(str2.strip('b'))#输出为:aabbccddaaa。无报错。