learn python the hard way (personal) -- Ex11-

Ex11:

input()接收一个python表达式作为输入,并将运算结果返回。

like = input('Do you like me?')
print("You say:", like)

如果要别人输入int: 

x = int(input())

如果你希望将输出的值转成字符串,可以使用 repr() 或 str() 函数来实现。

age = input()
print(">>> age =", repr(age))

 

 

Ex12:

height = input(f"You're {age}? Nice. How tall are you?")

在cmd中输入 python3.6 -m pydoc input 看结果会如何。

Ex13:

from sys import argv # argv is the "argument variable"
# read the WYSS(What You Should See) section for how to run this
script, first, second, third = argv # unpacked argv, it gets assigner to 4 variables you can wrk with

print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)

import sys package and get the argv feature from the package

argument variable:参数变量

需要这样运行:

$ python3.6 ex13.py first 2nd 3rd

运行结果:

The script is called: ex13.py
Your first variable is: first
Your second variable is: 2nd
Your third variable is: 3rd

Study Drills

Combine input with argv to make a script that gets more input from a user. 

 

Ex14:

prompt = f'{script} >'
computer = input(prompt)

用prompt代替字符串,不用每次去输入。

Study Drills

  1. Find out what the games Zork and Adventure were. Try to find a copy and play it.

https://github.com/iamjawa/zork-py/blob/master/zork.py#L97

 

Ex15:(very important)

open file

We don't want to use "hard code", so the solution is to use argv or input to ask the user what file to open.

from sys import argv

script, filename = argv

txt = open(filename, encoding="utf-8")
# encoding="utf-8"  is used when there are strange strings

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

search for python3.6 -m pydoc open in cmd to find out what open means

可以打开自己

Study Drills

  1. Start python3.6 to start the python3.6 shell, and use open from the prompt just like in this program. Notice how you can open files and run read on them from within python3.6?
  2. Have your script also call close() on the txt and txt_again variables. It's important to close files when you are done with them.

 

Ex16:

  • close -- Closes the file. Like File->Save.. in your editor.

一般来说都要close,不然容易崩溃。

  • read -- Reads the contents of the file. You can assign the result to a variable.
  • readline -- Reads just one line of a text file.
  • truncate -- Empties the file. Watch out if you care about the file.
  • write('stuff') -- Writes "stuff" to the file.
  • seek(0) -- Move the read/write location to the beginning of the file.
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

Study Drills

There's too much repetition in this file. Use strings, formats, and escapes to print out line1, line2, and line3 with just one target.write() command instead of six.

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

If you open the file with 'w' mode, then do you really need the target.truncate()? Read the documentation for Python's openfunction and see if that's true.

 'w'       open for writing, truncating the file first

 

Common Student Questions

What modifiers to the file modes can I use?

The most important one to know for now is the + modifier, so you can do 'w+', 'r+', and 'a+'. This will open the file in both read and write mode and, depending on the character use, position the file in different ways.

 

Ex17:

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print(f"Copying from {from_file} to {to_file}")

# we could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()
#indata = open(from_file).read()
print(f"The input file is {len(indata)} bytes long")

print(f"Dose the output file exist? {exists(to_file)}")
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()

out_file = open(to_file, 'w')
out_file.write(indata)

print("Alright, all done.")

out_file.close
in_file.close

try_file = open('17_3.txt','w')
try_file.write(input('>'))

copy 和 exists

$ # first make a sample file
$ echo "This is a test file." > test.txt
$ # then look at it
$ cat test.txt
This is a test file.
$ # now run our script on it
$ python3.6 ex17.py test.txt new_file.txt

 echo to make a file, and cat to show the file.

You probably did something like this, indata = open(from_file).read(), which means you don't need to then do in_file.close() when you reach the end of the script. It should already be closed by Python once that one line runs.

自己做时,出现了以下错误提示:

Traceback (most recent call last):
  File "17.py", line 10, in <module>
    indata = in_file.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence

参考了这个两个网站的详细解释。

https://www.crifan.com/summary_python_unicodedecode_error_possible_reasons_and_solutions/

https://blog.csdn.net/wang7807564/article/details/78164855

in_file = open(from_file,'r',encoding='gbk',errors = 'ignore')

只修改,encoding =  ‘gbk' ,不可行;将第二个参数errors从strict修改为ignore。解决了问题,但还是不懂为什么在最开始的尝试时是没有问题的,后面在自己做修改的时候才出现了问题,回溯了之前的版本也还是有问题。

更新:最后发现问题在于编码问题,最开始创建txt文档是在文件夹中用右键新建的,编码格式为ANSI。之后使用echo新建txt,而使用的是Windows中文系统,输入法的编码为gbk,故会出现这样的问题。可以修改相应的txt编码格式为ANSI或UTF-8即可解决这个问题。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值