发布于2020-03-03 20:55 阅读(1427) 评论(0) 点赞(7) 收藏(1)
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.
""")
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.
代码
# 将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())
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.
输出结果
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.
from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here's your file {filename}:")
print(txt.read())
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.
filename = input("Type the filename:")
txt = open(filename)
print(f"Here is your file {filename}:")
print(txt.read())
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:
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
- 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
- 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'
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()
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.
语法
open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True)
运行
打开file并返回对应的file object。若文件不能打开,则触发OSError。
参数
常用的是file,mode和encoding
file
file 是一个 path-like object,表示将要打开的文件的路径(绝对路径或者当前工作目录的相对路径),也可以是要被封装的整数类型文件描述符。
- file指定了要打开的文件名称
- file的数据类型为字符串
- file也包含了文件所在的存储路径,存储路径可以是相对路径,也可以是绝对路径。
mode
mode指定了文件的打开模式,也就是设定文件的打开权限。
打开模式 | 模式描述 |
---|---|
r(默认) | 以只读方式打开文件。指针位置:文件开头 |
w | 以只写方式打开文件。先清空,后写入 |
a | 以追加只写方式打开文件。指针位置:文件结尾 |
r+ | 以读写方式打开文件。指针位置:文件开头 |
w+ | 以读写方式打开文件。先清空,后写入 |
a+ | 以追加读写方式打开文件。指针位置:文件结尾 |
b(rb、rb+、wb、wb+、ab、ab+) | 以二进制格式打开文件,其余与以上内容相同 |
- 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内核的系统中,打开一个文件,便会返回一个文件描述符。
注意,当操作文件结束后,必须调用 close() 函数手动将打开的文件进行关闭,这样可以避免程序发生不必要的错误。
适用文件
语法
file.read([size])
参数
size 表示的是一次最多可读取的字符(或字节)数,因此,即便设置的 size 大于文件中存储的字符(字节)数,read() 函数也不会报错,它只会读取文件中所有的数据。
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()
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.
# 将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()
from sys import argv
script, filename = argv
txt = open(filename)
print(txt.read())
txt.close()
PS D:\pythonp> python ex16.1.py test.txt
A
B
C
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()
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.
找出需要给open多传入一个’w’参数的原因。提示:open对文件的写入操作态度是安全第一,所以只有特别指定以后,它才会进行写入操作。
确保操作完成后文件内的内容仅为本次操作写入的内容。
若文件本身已存在,则清空文件原本内容后,从头写入本次操作写入的内容
如果你用’w’模式打开文件,那么你是不是还需要 target. truncate()呢?阅读下 Python的open函数的文档找找答案。
不需要,理由如上条
作者:坚持才能胜利
链接:https://www.pythonheidong.com/blog/article/241131/f1289185111b6d67ffd0/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!