请问大家这个地址是对的,为啥会报错呀?跟着B站自学的,谢谢!
def print_file_info(file_name):
f = None
try:
f = open(file_name)
content = f.read()
print(content)
except Exception as e:
print(f'程序出现异常了{e}')
finally:
if f :
f.close()
if __name__ == '__main__':
print_file_info(r"C:\Users\Administrator\Desktop\bill.txt")
和明显是字符编码问题,需要在打开文件的时候设置下
# -*- coding:utf-8 -*-
def print_file_info(file_name):
f = None
try:
f = open(file_name,'r',encoding='gbk') #如果gbk不行,就试试 utf-8
content = f.read()
print(content)
except Exception as e:
print(f'程序出现异常了{e}')
finally:
if f:
f.close()
if __name__ == '__main__':
print_file_info(r"C:\Users\Administrator\Desktop\bill.txt")
要么指定编码(f = open(file_name, encoding='utf-8') ),要么忽略不能解码的字节(f = open(file_name, errors='ignore'))
1.结果图
2.结果图
问题的原因是在使用open
函数打开文件时,没有指定文件的打开模式。
在Python中,open
函数默认以只读模式打开文件,而在你的代码中,在open
函数里只传入了文件名,没有指定打开模式。因此,当程序尝试打开文件时,会抛出TypeError
异常。
为了解决这个问题,你可以在调用open
函数时,指定文件的打开模式。常用的文件打开模式有:
'r'
:只读模式'w'
:写入模式,如果文件不存在则创建,存在则清空内容'a'
:追加模式,如果文件不存在则创建'x'
:独占创建模式,如果文件已存在,则抛出FileExistsError
异常'b'
:以二进制模式打开文件't'
:以文本模式打开文件,这是默认模式根据你的代码逻辑,你可以将open
函数的调用改为如下方式:
f = open(file_name, 'r')
这样,就明确指定了打开模式为只读模式,即可解决报错的问题。
修改后的代码如下:
def print_file_info(file_name):
f = None
try:
f = open(file_name, 'r')
content = f.read()
print(content)
except Exception as e:
print(f'程序出现异常了{e}')
finally:
if f:
f.close()
if __name__ == '__main__':
print_file_info(r'C:\Users\Administrator\Desktop\bill.txt')
请注意,使用open
函数打开文件后,记得在不使用文件时进行关闭,这是良好的编程习惯。你可以通过f.close()
在finally
块中进行关闭。