大家好,本文将围绕笨办法学python 3电子书下载展开说明,笨办法学python3进阶篇pdf是一个很多人都想弄明白的事情,想搞清楚笨办法学python第三版需要先了解以下几个事情。
Source code download: 本文相关源码
学习目标:
处理文件需要非常仔细,如果不仔细可能会把文件弄坏或清空
用脚本“打开”文件,然后将其打印出来
代码如下
from sys import argv
#调用sys模块的argv函数
s,filename = argv,'ex15_sample.txt'
#参数命名,如果不命名filename参数,就无法读取txt
txt = open(filename)
#命名变量txt是打开打开filename,而filename的参数是'ex15_sample.txt'
print(f"Here's your life{filename}:")
#用(f'')显示字符串时,将把每个变量都替换为其值,替换值:{filename}
print(txt.read())
#read函数可以读取txt文件
print("Type the filename again:")
file_again = input(">")
txt_again = open(file_again)
#again函数,没查到怎么用,估计就是重复一下的意思喽
print(txt_again.read())
结果输出
Here's your lifeex15_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 and lots of fun to have in here.
进程已结束,退出代码0
巩固练习:
1. 每行进行注释
2. 删掉10-15行,结果:
Here's your life 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.
3. 用input函数读取文件名
from sys import argv
s,filename = argv,'ex15_sample.txt'
txt = open(filename)
print('input type = "ex15_sample.txt"')
print(f"Here's your life {filename}:")
print(txt.read())
print("Type the filename again:")
file_again = input(">")
txt_again = open(file_again)
print(txt_again.read())
结果输出
input type = "ex15_sample.txt"
Here's your life 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 and lots of fun to have in here.
进程已结束,退出代码0
4. 读取文件相关的函数
Tips:
- 文件内容与文件对象
txt = open(filename)
#返回的是文件的内容吗?不是
#返回的是文件对象(file object)
- python不会限制打开了几次文件,有时候打开多次文件也是必需的。
from sys import argv
#是什么意思?
#sys是个软件包,从软件包提取argv这个特性
, ex15_sample.txt = argv
#这样不灵,是错的
#需要命名文件名字,而不是直接放进去