程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-06(1)

*笨办法学python3 学习笔记 习题14-16

发布于2020-03-03 20:55     阅读(1226)     评论(0)     点赞(7)     收藏(1)


习题14

from sys import argv

script, user_name, age = argv
prompt = "Your answer: "

print(f"Hi {user_name}, I'm the {script} script.")
print("I'd like to ask you a few questions.")

print(f"Do you like me {user_name}?")
likes = input(prompt)

print(f"Where do you live {user_name}?")
lives = input(prompt)

print("What kind of computer do you have?")
computer = input(prompt)

print(f"""
Alright, so you said {likes} about liking me.
You live in {lives}.    Not sure where that is.
You are {age} years old now.
And you have a {computer} computer.     Nice.
""")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
PS D:\pythonp> python .\ex14.py h 24
Hi h, I'm the .\ex14.py script.
I'd like to ask you a few questions.
Do you like me h?
Your answer: y
Where do you live h?
Your answer: C
What kind of computer do you have?
Your answer: m

Alright, so you said y about liking me.
You live in C.    Not sure where that is.
You are 24 years old now.
And you have a m computer.     Nice.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14


习题15 读取文件


代码

# 将sys模块导入
from sys import argv

# 将argv解包,将所有的参数依次赋值给左边的变量
script, filename = argv

# 打开filename文件,并将该文件赋值给txt
txt = open(filename)

# 打印格式化字符串,“这是你的文件xxx:”
print(f"Here's your file {filename}:")
# 读取并打印txt的全部内容
print(txt.read())

# 打印“再次输入文件名”
print("Type the filename again")
# 打印“>”符号,并将输入的内容赋值给file_again
file_again = input(">")

# 打开file_again文件,并将文件赋值给txt_again
txt_again = open(file_again)

# 读取并打印txt_again的全部内容
print(txt_again.read())

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

ex15_sample.txt内容

This is stuff I typed into a file.
It is really a cool stuff.
Lots and lots fun to have in here.
  • 1
  • 2
  • 3

输出结果

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

Type the filename again
>ex15_sample.txt
This is stuff I typed into a file.
It is really a cool stuff.
Lots and lots fun to have in here.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  1. 删掉第10~15行用到 input的部分,再运行一遍脚本。
from sys import argv

script, filename = argv

txt = open(filename)

print(f"Here's your file {filename}:")
print(txt.read())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
PS D:\pythonp> python ex15.1.py ex15_sample.txt
Here's your file ex15_sample.txt:
This is stuff I typed into a file.
It is really a cool stuff.
Lots and lots fun to have in here.
  • 1
  • 2
  • 3
  • 4
  • 5
  1. 只用 input写这个脚本,想想哪种获取文件名称的方法更好,为什么。
filename = input("Type the filename:")

txt = open(filename)

print(f"Here is your file {filename}:")
print(txt.read())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
PS D:\pythonp> python .\ex15.2.py
Type the filename:ex15_sample.txt
Here is your file ex15_sample.txt:
This is stuff I typed into a file.
It is really a cool stuff.
Lots and lots fun to have in here.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  1. 再次运行 python3.6,在提示符下使用open打开一个文件。注意这种在 python里边打开文件执行read的方式。

错误1:

PS D:\pythonp> python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> txt=open(ex15_sample.txt)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ex15_sample' is not defined
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • txt=open(ex15_sample.txt)
    文件名没有加路径

错误2

>>> txt=open(d:/pythonp/ex15_sample.txt)
  File "<stdin>", line 1
    txt=open(d:/pythonp/ex15_sample.txt)
              ^
SyntaxError: invalid syntax
  • 1
  • 2
  • 3
  • 4
  • 5
  • open()函数中路径及文件名没有加引号
    我也不知道为啥,反正加了就可以正常运行了,不是说变量名不加引号么?因为这是文件名?可是当其保存为py文件而不是在python运行下的时候,也没加引号就可以正常运行啊?

正确版本:

PS D:\pythonp> python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> txt=open("d:/pythonp/ex15_sample.txt")
>>> txt.read()
'This is stuff I typed into a file.\nIt is really a cool stuff.\nLots and lots fun to have in here.\n'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  1. 让你的脚本针对txt和txt again变量也调用一下close()。处理完文件后需要将其关闭,这是很重要的一点。
from sys import argv

script, filename = argv

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())

txt.close()
txt_again.close()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
PS D:\pythonp> python ex15.3.py ex15_sample.txt
Here's your file ex15_sample.txt:
This is stuff I typed into a file.
It is really a cool stuff.
Lots and lots fun to have in here.

Type the filename again
>ex15_sample.txt
This is stuff I typed into a file.
It is really a cool stuff.
Lots and lots fun to have in here.

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

知识点

open()函数

  • 语法
    open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True)

  • 运行
    打开file并返回对应的file object。若文件不能打开,则触发OSError。

    • file object——文件对象
      对外提供面向文件 API 以使用下层资源的对象(带有 read() 或 write() 这样的方法)。
  • 参数

    常用的是file,mode和encoding

    • file
      file 是一个 path-like object,表示将要打开的文件的路径(绝对路径或者当前工作目录的相对路径),也可以是要被封装的整数类型文件描述符。

      • path-like object——路径类对象
        代表一个文件系统路径的对象。
      • file指定了要打开的文件名称
      • file的数据类型为字符串
      • file也包含了文件所在的存储路径,存储路径可以是相对路径,也可以是绝对路径。
    • mode

      mode指定了文件的打开模式,也就是设定文件的打开权限。

打开模式 模式描述
r(默认) 以只读方式打开文件。指针位置:文件开头
w 以只写方式打开文件。先清空,后写入
a 以追加只写方式打开文件。指针位置:文件结尾
r+ 以读写方式打开文件。指针位置:文件开头
w+ 以读写方式打开文件。先清空,后写入
a+ 以追加读写方式打开文件。指针位置:文件结尾
b(rb、rb+、wb、wb+、ab、ab+) 以二进制格式打开文件,其余与以上内容相同

图源网络

  • buffering
    • buffering用于指定打开文件所用的缓冲方式。
    • 缓冲是指用于读取文件的缓冲区,缓冲区就是一段内存区域。设置缓冲区的目的是先把文件内容读取到缓冲区,可以减少CPU读取磁盘的次数。
buffering值 缓冲方式
0 不缓冲
1 只缓冲一行数据
-1 使用系统默认缓冲机制(默认值)
大于1的值 使用给定值作为缓冲区大小
  • encoding

    • encoding用于指定文件的编码方式,默认采用utf-8,一般使用utf8或gbk。
    • 编码方式主要是指文件中的字符编码。
    • win系统默认是gbk编码的,所以桌面生成的TXT之类的都是gbk编码的
  • errors

    • errors的取值一般有strict,ignore
    • 当取strict的时候,字符编码出现问题的时候,会报错
    • 当取ignore的时候,编码出现问题,程序会忽略而过,继续执行下面的程序。
  • newline
    可以取的值有None, \n, \r, ‘’, ‘\r\n’ ,用于区分换行符,但是这个参数只对文本模式有效;

  • closefd
    取值与传入的文件参数有关,默认情况下为True,传入的file参数为文件的文件名,取值为False的时候,file只能是文件描述符,什么是文件描述符,就是一个非负整数,在Unix内核的系统中,打开一个文件,便会返回一个文件描述符。

tips:

  • file.close()

注意,当操作文件结束后,必须调用 close() 函数手动将打开的文件进行关闭,这样可以避免程序发生不必要的错误。


read()函数

  • 适用文件

    • 对于借助 open() 函数,并以可读模式(包括 r、r+、rb、rb+)打开的文件,可以调用 read() 函数逐个字节(或者逐个字符)读取文件中的内容。
      • 如果文件是以文本模式(非二进制模式)打开的,则 read() 函数会逐个字符进行读取
      • 如果文件以二进制模式打开,则 read() 函数会逐个字节进行读取。
  • 语法
    file.read([size])

  • 参数

    • file
      表示已打开的文件对象;
    • size
      可选参数,用于指定一次最多可读取的字符(字节)个数,如果省略,则默认一次性读取所有内容。

      size 表示的是一次最多可读取的字符(或字节)数,因此,即便设置的 size 大于文件中存储的字符(字节)数,read() 函数也不会报错,它只会读取文件中所有的数据。



习题16 读写文件

from sys import argv

script, filename = argv

print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")

input("?")

print("Opening the file...")
target = open(filename, "w")

print("Truncating the file. Goodbye!")
target.truncate()

print("Now I'm going to ask you for three lines.")

line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")

print("I'm going to write these to the file.")

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print("And finally, we close it.")
target.close()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
PS D:\pythonp> python ex16.py test.txt
We're going to erase test.txt.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?^C
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: A
line 2: B
line 3: C
I'm going to write these to the file.
And finally, we close it.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

  1. 如果你觉得自己没有弄懂,用我们的老办法,在每一行之前加上注释,为自己理清思路。一条简单的注释将帮你理解,或者至少让你知道自己究竞哪里没弄明白需要多下功夫。
# 将sys模块导入
from sys import argv

# 将argv解包,将参数依次赋值给左边的变量
script, filename = argv

# 打印f-字符串:我们将要擦除给定文件名内的内容
print(f"We're going to erase {filename}.")
# 打印字符串:如果你不想要这样,点击CTRL-C (^C)
print("If you don't want that, hit CTRL-C (^C).")
# 打印字符串:如果你想要这样,点击RETURN
print("If you do want that, hit RETURN.")

# 打印“?”并获得输入内容
input("?")

# 打印字符串:正在打开文件……
print("Opening the file...")
# 以只写方式打开文件并返回相应的文件对象,并将其赋值给左边的target变量
target = open(filename, "w")

# 打印字符串:删截文件。再见!
print("Truncating the file. Goodbye!")
# 清空target文件
target.truncate()

# 打印字符串:现在我要问你三句话
print("Now I'm going to ask you for three lines.")

# 打印“line 1:”,获得输入内容并将其赋值给line1
line1 = input("line 1: ")
# 打印“line 2:”,获得输入内容并将其赋值给line2
line2 = input("line 2: ")
# 打印“line 3:”,获得输入内容并将其赋值给line3
line3 = input("line 3: ")

# 打印字符串:我要将这些写入文件
print("I'm going to write these to the file.")

# 将line1写入target
target.write(line1)
# 将\n换行符写入target
target.write("\n")
# 将line2写入target
target.write(line2)
# 将\n换行符写入target
target.write("\n")
# 将line3写入target
target.write(line3)
# 将\n换行符写入target
target.write("\n")

# 打印字符串:最终,我们关闭文件
print("And finally, we close it.")
# 关闭target文件
target.close()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  1. 写一段与上一个习题类似的脚本,使用read和argv读取你刚才新建的文件。
from sys import argv

script, filename = argv

txt = open(filename)

print(txt.read())

txt.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
PS D:\pythonp> python ex16.1.py test.txt
A
B
C

  • 1
  • 2
  • 3
  • 4
  • 5
  1. 这个文件中重复的地方太多了。试着用一个 target. write()将1ine1、1ine2和1ine3打印出来,替换掉原来的6行代码。你可以使用字符串、格式化字符和转义字符。
from sys import argv

script, filename = argv

print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")

input("?")

print("Opening the file...")
target = open(filename, "w")

print("Truncating the file. Goodbye!")
target.truncate()

print("Now I'm going to ask you for three lines.")

line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")

print("I'm going to write these to the file.")

target.write(f"{line1} \n {line2} \n {line3} \n")

print("And finally, we close it.")
target.close()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
PS D:\pythonp> python ex16.2.py test1.txt
We're going to erase test1.txt.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?CTRL-C
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: AA
line 2: BB
line 3: CC
I'm going to write these to the file.
And finally, we close it.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  1. 找出需要给open多传入一个’w’参数的原因。提示:open对文件的写入操作态度是安全第一,所以只有特别指定以后,它才会进行写入操作。

    确保操作完成后文件内的内容仅为本次操作写入的内容。
    若文件本身已存在,则清空文件原本内容后,从头写入本次操作写入的内容

  2. 如果你用’w’模式打开文件,那么你是不是还需要 target. truncate()呢?阅读下 Python的open函数的文档找找答案。

    不需要,理由如上条


知识点

函数

  • close()
    关闭文件。跟你的编辑器中的“文件”→“保存”是一个意思。
  • read()
    读取文件的内容。你可以把结果赋给一个变量。
  • readline()
    只读取文本文件中的一行。
  • truncate()
    清空文件,请小心使用该命令。
  • write(‘stuff’)
    将“stuff”写入文件。
  • seek(0)
    将读写位置移动到文件开头


所属网站分类: 技术文章 > 博客

作者:坚持才能胜利

链接:https://www.pythonheidong.com/blog/article/241131/f1289185111b6d67ffd0/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

7 0
收藏该文
已收藏

评论内容:(最多支持255个字符)