笨办法学python3进阶篇pdf,笨办法学python第三版

本文介绍了如何下载《笨办法学Python3》进阶篇的PDF,并通过实例讲解了基础的文件操作,如使用sys.argv获取用户输入的文件名,以及open函数创建文件对象。过程中还涉及到了Python中处理文件的注意事项和相关函数的使用技巧。
摘要由CSDN通过智能技术生成

大家好,本文将围绕笨办法学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:

  1. 文件内容与文件对象
txt = open(filename)
#返回的是文件的内容吗?不是
#返回的是文件对象(file object)
  1. python不会限制打开了几次文件,有时候打开多次文件也是必需的。
from sys import argv
#是什么意思?
#sys是个软件包,从软件包提取argv这个特性
, ex15_sample.txt = argv
#这样不灵,是错的
#需要命名文件名字,而不是直接放进去
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值