笨办法学python3 LPTHW系列Exercise16-20

Exercise 16. Reading and Writing Files

各种与文件相关的命令:

命令含义
close关闭并保存文件
read读取文件内容,可以把结果赋给一个变量
readline只读取文本文件中的一行
truncate清空文件,不要随便使用
write(‘stuff’)将stuff写入文件
seek(0)将读写位置移动到文件开头

文件读写有点意思,示例:

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

但是w+,r+等模式,我尝试了下,好像有点问题,不知道他为什么从文件末尾开始写入,不应该是a+才是末尾写入吗?

注:现在我懂了,我重新尝试了w+模式,发现你write完之后,读取的位置就会变化,所以再输出就没有了,只要用seek重新定位到开头就好了。

Exercise 17. More Files

这一节讲了讲怎么将A文件的内容复制给B文件,示例:

from sys import argv
from os.path import exists#这里也可以没有,因为没用到exists,该函数用于判断一个文件是否存在,返回值是布尔类型

script, from_file, to_file = argv

print(f"Copying from {from_file} to {to_file}")
indata = open(from_file).read()

out_file = open(to_file, 'w')
out_file.write(indata)
out_file.close()
print("Alright, all done.")

Exercise 18. Names, Variables, Code, Functions

这一节主要讲怎么定义函数和调用函数,很简单的,只要一行def即可:

# this one is like your scripts with argv
def print_two(*args):
    arg1, arg2 = args
    print(f"arg1: {arg1}, arg2: {arg2}")

# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
    print(f"arg1: {arg1}, arg2: {arg2}")

# this just takes one argument
def print_one(arg1):
    print(f"arg1: {arg1}")

# this one takes no arguments
def print_none():
    print("I got nothin'.")


print_two("Zed", "Shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()

分别讲了四种不同的函数定义:使用args列表来接收参数,直接接收参数,只有一个参数,和无参数。

Exercise 19. Functions and Variables

这一节讲了给函数传值的几种方式,可以是数字,可以是变量,还可以是表达式。
示例:

def cheese_and_crackers(cheese_count, boxes_of_crackers):
    print(f"You have {cheese_count} cheeses!")
    print(f"You have {boxes_of_crackers} boxes of crackers!")
    print("Man that's enough for a party!")
    print("Get a blanket.\n")


print("We can just give the function numbers directly:")
cheese_and_crackers(20, 30)


print("OR, we can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50

cheese_and_crackers(amount_of_cheese, amount_of_crackers)


print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)


print("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)

Exercise 20. Functions and Files

这一节主要讲使用函数来完成前面讲过的读取操作,读整个文件,读其中一行,都可以写成函数,方便复用:

from sys import argv

script, input_file = argv

def print_all(f):
    print(f.read())

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print(line_count, f.readline(), end = '')

current_file = open(input_file)

print("First let's print the whole file:\n")

print_all(current_file)

print("Now let's rewind, kind of like a tape.")

rewind(current_file)

print("Let's print three lines:")

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值