|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 huyanmin 于 2021-5-25 18:12 编辑
def file_view(file_name, line_num):
print('\n文件%s的前%s的内容如下:\n' % (file_name, line_num))
f = open(file_name)
for i in range(int(line_num)):
print(f.readline(), end= '')
f.close()
file_name = input(r'请输入要打开的文件(C:\\test.txt):')
line_num = input('请输入需要显示该文件前几行:')
file_view(file_name, line_num)
'''
= RESTART: C:\Users\Administrator\AppData\Local\Programs\Python\Python39\0000.py
请输入要打开的文件(C:\\test.txt):c:\record.txt #此处输入这个绝对路径正确执行
请输入需要显示该文件前几行:4
文件c:\record.txt的前4的内容如下:
小客服:小甲鱼,今天有客户问你有没有女朋友?
小甲鱼:咦??
小客服:我跟她说你有女朋友了!
小甲鱼:。。。。。。
>>>
= RESTART: C:\Users\Administrator\AppData\Local\Programs\Python\Python39\0000.py
请输入要打开的文件(C:\\test.txt):C:\Users\Administrator\Desktop\record.txt #此处输入桌面文件的绝对路径就报错
请输入需要显示该文件前几行:5
文件C:\Users\Administrator\Desktop\record.txt的前5的内容如下:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\0000.py", line 11, in <module>
file_view(file_name, line_num)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\0000.py", line 3, in file_view
f = open(file_name)
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Administrator\\Desktop\\record.txt'
>>>
>>>
= RESTART: C:\Users\Administrator\AppData\Local\Programs\Python\Python39\0000.py
请输入要打开的文件(C:\\test.txt):c:\\users\\administrator\\desktop\\record.txt #输入双斜杠的绝对路径也报错(下载到桌面的txt文件)
请输入需要显示该文件前几行:5
文件c:\\users\\administrator\\desktop\\record.txt的前5的内容如下:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\0000.py", line 11, in <module>
file_view(file_name, line_num)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\0000.py", line 3, in file_view
f = open(file_name)
FileNotFoundError: [Errno 2] No such file or directory: 'c:\\\\users\\\\administrator\\\\desktop\\\\record.txt'
>>>
'''
可以的,你确保你的文件是存在的吗??
>>> path=r"C:\Users\Administrator.USER-20120726TE\Desktop\112.xlsx"
>>> open(path,"r")
<_io.TextIOWrapper name='C:\\Users\\Administrator.USER-20120726TE\\Desktop\\112.xlsx' mode='r' encoding='cp936'>
>>> path="C:\\Users\\Administrator.USER-20120726TE\\Desktop\\112.xlsx"
>>> open(path,"r")
<_io.TextIOWrapper name='C:\\Users\\Administrator.USER-20120726TE\\Desktop\\112.xlsx' mode='r' encoding='cp936'>
>>>
|
|