笨方法学Python 习题 15: 读取文件

本文介绍了Python中读取文件的技巧,包括注释文件功能、理解open()和read()的区别、使用pydoc探索文件方法,以及强调在处理文件后调用close()的重要性。此外,解答了关于文件对象、命令行运行Python代码、sys.argv用法和多次打开文件不报错的疑问。

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

#!usr/bin/python
# -*-coding:utf-8-*-

from sys import argv

script, filename = argv
#获取参数 给script赋值ex15.py filename赋值ex15_sample.txt 

txt = open(filename)
#打开 ex15_sample.txt文本

print ("Here's your file %r:" % filename)
#打印 Here's your file ex15_sample.txt
print (txt.read())
#打印 ex15_sample.txt文本内容
print ("I'll also ask you to type it again:")
#打印 I'll also ask you to type it again:
file_again = input("> ")
#输入为file_again赋值
txt_again = open(file_again)
#打开file_again文本
print (txt_again.read())
#打印file_again文本


运行结果如下:

python ex15.py ex15_sample.txt 
Here's your file 'ex15_sample.txt':
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.


Type the filename again:
> ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots an
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值