笨办法学python 习题20(函数和文件)笔记

这篇博客探讨了在Python中使用`import sys`和`from sys import argv`的区别,并展示了如何处理文件操作,包括读取文件、重置文件指针以及按行打印文件内容。博主遇到的编码问题在于Windows10默认的UTF-16LE编码,改为UTF-8后得以解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from sys import argv
# import sys 与from sys import argv的作用与区别(https://blog.youkuaiyun.com/weixin_41321234/article/details/79099233)
script,input_file = argv

def print_all(f):
    print(f.read())# 读取文件

def rewind(f):
    f.seek(0)# 从文件开头开始读

def print_a_line(line_count,f):
    print(line_count,f.readline())

current_file = open(input_file)

print("First let's print the whole file:\n")

print_all(current_file)# 直接调用current_file函数

print("Now let's rewind,kind of like a tape.")

rewind(current_file)

print("Let's print three lines:")

current_line = 1
print_a_line(current_line,current_file)

current_line = current_line + 1
print_a_line(current_line,current_file)

current_line = current_line + 1
print_a_line(current_line,current_file)

第一次运行结果
现实
现实解码错误,把在网上能搜到的解决办法都试了一遍,结果要么还是现实解码错误,要么就是乱码;之后一个python群的老师建议我在文本中修改编码格式,我打开文本文件发现,windows10系统默认的编码格式是UTF-16LE,改成UTF-8后再次运行,终于运行成功。
在这里插入图片描述
在这里插入图片描述
修改编码后的运行结果
在这里插入图片描述
对于seek()的作用,详见http://c.biancheng.net/view/4780.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值