文件和异常
文件中读取数据
读取整个文件(文本文件)
首先创建一个文本文件,后缀名为.txt,如digits.txt,打开方式如下:
with open ('digits.txt') as file_object:
contents = file_object.read()
print(contents)
open()函数接受一个参数,也就是需要打开文件的名称,注意一定要是文件在程序文件所属目录中的文件全称
with关键字将在不需要访问文件时将其关闭
文件路径
并不是所有的文件都储存在程序文件所属目录中,以此我们可以使用绝对路径对文件进行直接访问,由于一般的文件绝对路径较长,因此可以将文件绝对路径储存在一个变量中,再作为open的参数传递进去
txt ='C:\\Users\\DELL\\code\\my text' # windows注意一定要是双斜杠,表示转义,否则报错
with open (txt)as file_object:
contents = file_object.read()
print(contents)
逐行读取
对指定文件逐行进行读取
filename = 'pi_digits.txt'
with open (filename)as file_object:
for line in file_object:
print(line.rstrip()) # 消除空行
创建一个包含各行内容的列表
使用关键字with时,open打开的文件只能在with代码块内使用,如果在with代码块外访问文件的内容可以将文件的各行存储在列表中,具体方法如下:
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines() # 创建列表成功,这里是readlines而不是readline,后者是对单行的每个字母创建列表
for line in lines: # 遍历
print(line.rstrip())
文件内容的使用
将文件读取到内存中后就可以对数据进行操作了,如将读取的圆周率全部转换为一行,中间没有空格
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip() #去除两端空格
print(pi_string)
课后习题
10-1Python学习笔记
filename = 'learning_python.txt'
with open(filename) as file_object:
read_1 = file_object.read()
print(read_1) # 读取整个文件
filename = 'learning_python.txt'
with open(filename) as file_object:
for line_1 in file_object:
print(line_1.rstrip()) # 遍历文件
filename = 'learning_python.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip()) # 存储列表打印
10-2C语言学习笔记
print(read_1.replace('python','C')) # 相应行更换即可
写入文件
写入空文件
python不仅可以读取文本文件,还可以创建新的文本文件,具体操作如下
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object('I love Running\n')
file_object('I love python\n')
- open后的两个实参前者是写入的文件名,后一个w表示写入,默认情况下是r(读取模式),此外还有a(附加模式),值得注意的是如果以w对文件进行操作,如果之前的文件名存在则会将之前的文件情况再写入
- 如果想多行写入,需要在每行后端加入换行的转义字符(\n)
- 如果想将数值存储在文本文件中,必须先将其转换为字符串型(str)
附加到文件
前面提到的附加模式(a)指的是不会在文件已有的情况下对文件内容进行清空,而是将写入内容加入到文件的末尾,如果文件不存在则会创建一个新的文件。
filename = 'programming.txt'
with open(filename,'a')as file_object:
file_object.write('I also love chasing\n')
课后习题
10-3访客
filename = 'guest.txt'
name = input('input your name:')
with open(filename,'w')as file_object:
file_object.write(name + '\n')
10-4访客名单
filename = 'guest_book.txt'
active = True
while active:
name = input('input your name:')
if name == '': # 如果输入的是空值,中断循环
break
else:
print('hello,' + name)
with open(filename,'a')as file_object:
file_object.write(name + '\n')
10-5关于编程的调查
filename = 'reason.txt'
while True:
reasons = input('why would you like programming:')
if reasons == '':
break
else:
with open(filename,'a')as file_object:
file_object.write(reasons + '\n')