Python 读取文件

本文介绍如何使用Python读取并打印文件内容。通过argv获取文件名,并利用open函数打开文件,最后通过read函数读取文件内容。同时演示了两次读取同一文件的过程。

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

学习目标:

提示:我们之前也试用过 input 和 argv 获取用户输入,这次我们来试试读取文件。这个实验涉及2个文件,一个是正常的脚本文件,另一个是纯的文本文件,我们先看看文本文件内的内容:

# cat python07_test.txt 
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

我们这次做的实验就是用我们的脚本“打开”上述txt文件,然后将其打印出来。


学习实例:

from sys import argv
# filename可以替换成我们要打开的文件
script, filename = argv
# open属于函数,用来打开某些文件
txt = open(filename)

print(f"Here's your file {filename}:")
print(txt.read())

print("Type the filename again:")
file_again = input("> ")

txt_again = open(file_again)

print(txt_again.read())

· 代码的1-3行使用argv来获取文件名,之后会看到open这个新的函数命令,我们把这个与input命令类似。

· 我们在第8行又看到了新的内容,read函数。我们从open获得的东西是一个file(文件),文件本身也有一些你给它的命令。它接受命令的方式是使用句点( . ),紧跟着你的命令名,然后再跟着类似open和input的参数。不同的是:当我们执行txt.read()时,你的意思其实是:“txt!执行你的read命令,无须任何参数!”

之后执行,我们能看到结果如下:

# python python07.py python07_test.txt 

Here's your file python07_test.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:
> python07_test.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

from sys import argv 这段话的意思:sys 是一个软件包,这句话的意思是从该软件包中取出argv这个特性。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值