笨办法学python16-26

exercise 16 读写文件

看起来代码就很长的样子
作业代码:

from sys import argv

script, filename = argv

print ("We're going to erase %r." %filename)   
print ("If you don't want that, hit CTRL-C(^C).")  #CTRL-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 C:\Users\Brenda\Desktop\Python学习路径资料\exercise>  python 1.py ex15_sample.txt
We're going to erase 'ex15_sample.txt'.
If you don't want that, hit CTRL-C(^C).
If you do want that, hit RETURN.
?RETURN
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: I love winner.
line 2: They have different type.
line 3: Forever.
I'm going to write these to the file.
And finally, we close it.

同时,打开文件,确实实现了txt文件内容的更新
疑问:1.print ("If you don't want that, hit CTRL-C(^C)."):无论在input行输入什么,都是往下执行的。(CTRL-C应该是能够直接中断进程的)

加分练习:
2.写一个和上一个练习类似的脚本,使用 read 和 argv 读取你刚才新建的文件。

加入这两行代码即可。

txt = open (filename,'r')
print (txt.read())

加分练习:3.文件中重复的地方太多了。试着用一个 target.write() 将 line1, line2, line3 打印出来,你可以使用字符串、格式化字符、以及转义字符。

from sys import argv

script, filename = argv

print ("We're going to erase %r." %filename)   
print ("If you don't want that, hit CTRL-C(^C).")  
print ("If you do want that, hit RE.")

input("?")

print ("Opening the file...")
target = open(filename, 'w')   #w是特殊字符串,表示文件的访问模式,
#w,写入write模式;r读取read模式,a追加append(只有特别指定才会进入写入模式,否则位阅读模式

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 ("%s\n%s\n%s"  %( line1 , line2 , line3))   #这一行进行了更改,加入了格式化字符串和转义字符。

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

txt = open (filename,'r')
print (txt.read())    #在关闭了文档之后,再次打开读取出文档内容,检验实验效果

exercise 17 更多文件操作

作业代码:

from sys import argv
from os.path import exists
#exists 将文件名字符串作为参数,如果存在返回TRUE,否则返回FALSE

script, from_file, to_file = argv

print ("Copying from %s to %s" % (from_file, to_file))

#we could do these two on one line too, how?
in_file = open (from_file)
indata = in_file.read()

print ("The input file is %d bytes long" % len (indata))   #len 以数字的形式返回传递字符串的长度

print ("Does the output file exist? %r"  % 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()

运行结果

Copying from ex15_sample.txt to 1.txt
The input file is 8 bytes long
Does the output file exist? True
Ready, hit RETURN to continue, CTRL-C to abort.

Alright, all done.

we could do these two on one line too, how?
indata = open(from_file).read()

exercise 18 命名、变量、代码、函数

函数 function!

  1. 它们给代码片段命名,就跟“变量”给字符串和数字命名一样。
  2. 它们可以接受参数,就跟你的脚本接受 argv 一样。
  3. 通过使用 #1 和 #2,它们可以让你创建“微型脚本”或者“小命令”。

自定义函数通过def进行定义。python中还含有内置函数。
代码:

#用def新建函数 define
#like argv
def print_two (*args):    #def + 定义的函数名称(参数):
    arg1, arg2 = args    #4个空格缩进,将参数解包
    print ("arg1: %r, arg2: %r" % (arg1, arg2))  #解包后每个参数打印出来
    
#OK, that *args is actually pointless, we can just do this 
def print_two_again (arg1, arg2):    #跳过整个参数解包的过程,直接使用变量名
    print ("arg1: %r, arg2: %r" % (arg1, arg2))
    
# this just takes one argument 接受单个参数
def print_one (arg1):    
    print ("arg1: %r" %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 ()

运行结果:

arg1: 'Zed', arg2: 'Shaw'
arg1: 'Zed', arg2: 'Shaw'
arg1: 'First!'
I got nothin'.

print_two ("Zed", "Shaw");print_two_again ("Zed", "Shaw");print_one ("First!");print_none ()
函数变量的定义必须放在最后,而不能放在最前方。

exercise 19 函数和变量

#函数里边的变量和脚本里边的变量之间是没有连接的
def cheese_and_crackers (cheese_count, boxes_of_crackers):
    print ("You have %d cheese!" % cheese_count)
    print ("You have %d 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)    #cheese_and_crackers为定义的函数 

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)

运行结果

We can just give the function numbers directly:
You have 20 cheese!
You have 30 boxes of crackers!
Man that's enough for a party!
Get a blanket.

OR, we can use variables from our script:
You have 10 cheese!
You have 50 boxes of crackers!
Man that's enough for a party!
Get a blanket.

We can even do math inside too:
You have 30 cheese!
You have 11 boxes of crackers!
Man that's enough for a party!
Get a blanket.

And we can combine the two, variables and math:
You have 110 cheese!
You have 1050 boxes of crackers!
Man that's enough for a party!
Get a blanket.

exercise 20 函数和文件

代码:

from sys import argv
script, input_file = argv  #argv解包,将所有参数以此赋予左边变量名

def print_all(f) :   #def定义函数,参数为f?
    print (f.read ())  #在f上调用read函数,并打印
    
def rewind(f):   #定义函数rewind,参数为f
    f.seek(0)   #f上调用seek函数,移动文件读取指针到指定位置,转到文件的0byte。
    
def print_a_line (line_count,f):   #定义print_a_line,参数为line_count和f
    print (line_count, f.readline())  #在f上调用readline,读取文本文件中的某一行
    
current_file = open(input_file)   #open()打开文件
print ("First let's print the whole file:\n")

print_all (current_file)   #调用函数print_all

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)

运行结果:

First let's print the whole file:

fe
we
dd
Now let's rewind, kind of like a tape.
Let's print three lines:
1 fe

2 we

3 dd

exercise 21 函数可以返回东西

代码:

def add (a,b):
    print ("ADDING %d +%d" % (a,b))
    return a+b
#调用了参数a,b,打印函数功能,做回传动作,将a,b的值返回return
def subtract (a,b):
    print ("SUBTRACTING %d -%d" % (a,b))
    return a-b 
    
def multiply (a,b):
    print ("MULTIPLYING %d *%d" % (a,b))
    return a*b 

def divide (a,b):
    print ("DIVIDING %d /%d" % (a,b))
    return a/b 
    
print ("Let's do some math with just functions!")

age = add(30,5)
height = subtract (78,4)
weight = multiply (90,2)
iq = divide (100,2)

print ("Age:%d, Height:%d, Weight:%d, IQ:%d" % (age, height, weight, iq))

print ("Here is a puzzle.")
what = add(age, subtract (height, multiply(weight,divide (iq,2))))

print ("That becomes : %d Can you do it by hand?" % what)  #加分习题2修改代码

运行结果:

Let's do some math with just functions!
ADDING 30 +5
SUBTRACTING 78 -4
MULTIPLYING 90 *2
DIVIDING 100 /2
Age:35, Height:74, Weight:180, IQ:50
Here is a puzzle.
DIVIDING 50 /2
MULTIPLYING 180 *25
SUBTRACTING 74 -4500
ADDING 35 +-4426
That becomes : -4391Can you do it by hand?

exercise 24 练习

代码:

print ("Let's practice everything.")
print (' You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')
#You'd need to know 'bout escapes with \ that do
#newlines and   tabs.  
#转义符\
poem = """
\tThe lovely world
with logic so firmly planted 
cannot discern \n the needs of love 
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""

print ("--------------")
print (poem)
print ("--------------")

five = 10-2+3-6
print ("This should be five: %s" % five)

def secret_formula (started):
    jelly_beans = started *500
    jars = jelly_beans /1000
    crates =jars /100
    return jelly_beans, jars, crates
    
start_point = 10000
beans, jars, crates = secret_formula(start_point)   #创建了一个新变量,用来存放函数的返回值

print ("With a starting point of : %d" %start_point)
print ("we'd have %d beans, %d jars, and %d crates." %(beans, jars, crates))

start_point = start_point /10
print ("We can also do that this way:")
print ("With a starting point of : %d" %start_point)
print ("we'd have %d beans, %d jars, and %d crates." %secret_formula(start_point))

结果:

Let's practice everything.
 You'd need to know 'bout escapes with \ that do
 newlines and    tabs.
--------------

        The lovely world
with logic so firmly planted
cannot discern
 the needs of love
nor comprehend passion from intuition
and requires an explanation

                where there is none.

--------------
This should be five: 5
With a starting point of : 10000
we'd have 5000000 beans, 5000 jars, and 50 crates.
We can also do that this way:
With a starting point of : 1000
we'd have 500000 beans, 500 jars, and 5 crates.

exercise 25 练习

def break_words (stuff):
    """This function will break up words for us."""
    words = stuff.split (' ')  #拆分 split '有空格'
    return words 
    
def sort_words (words):
    """sorts the words."""
    return sorted (words)    #按照首字母顺序进行排序
    
def print_first_word (words):
    """Prints the first word after popping it off."""
    word = words.pop(0)     #words.pop定位顺序,第0个
    print  (word)
   
def print_last_word (words):
    """Prints the last word after popping it off."""
    word = words.pop(-1)    #words.pop定位顺序,最后一个
    print (word)
    
def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)
    return sort_words
    
def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words (sentence)
    print_first_word(words)
    print_last_word(words)

exercise 26 改错

import  ex2   #去掉#
def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

def sort_words(words):
    """Sorts the words."""
    return sorted(words)

def print_first_word(words):   # 加上":"
    """Prints the first word after popping it off."""
    word = words.pop(0)  #pop(0)
    print (word)

def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1)   #加上“)”
    print (word)

def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)
    return sort_words(words)

def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

print ("Let's practice everything.")
print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')
#在python3中,print("")
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explantion
\n\t\twhere there is none.
"""

print ("--------------")
print (poem)
print ("--------------")

five = 10 - 2 + 3 - 5
print ("This should be five: %s" % five)

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000  #除法是“/”
    crates = jars / 100
    return jelly_beans, jars, crates

start_point = 10000
beans, jars, crates = secret_formula(start_point)  # jelly_beans =  start_point 

print ("With a starting point of: %d" % start_point)
print ("We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates))

start_point = start_point / 10

print ("We can also do that this way:")
print ("We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point))   #  start_point拼写 括号

sentence = "All god\tthings come to those who weight."  #good things

words = ex2.break_words(sentence)
sorted_words = ex2.sort_words(words)

print_first_word(words)
print_last_word(words)
print_first_word(sorted_words)   # 去掉print前面的 .
print_last_word(sorted_words)
sorted_words = ex2.sort_sentence(sentence)
print (sorted_words)   # print

print_first_and_last(sentence)  # print print_first_and_last 拼写
print_first_and_last_sorted(sentence)   #indent print first_a_last_sorted(sentence) 空格
Let's practice everything.
You'd need to know 'bout escapes with \ that do
 newlines and    tabs.
--------------

        The lovely world
with logic so firmly planted
cannot discern
 the needs of love
nor comprehend passion from intuition
and requires an explantion

                where there is none.

--------------
This should be five: 6
With a starting point of: 10000
We'd have 5000000 jeans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crabapples.
All
weight.
All
who
['All', 'come', 'god\tthings', 'those', 'to', 'weight.', 'who']
All
weight.
All
who

移除对ex2的引用也可以,把全篇的ex2相关都删去。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,163评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,301评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,089评论 0 352
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,093评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,110评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,079评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,005评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,840评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,278评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,497评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,667评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,394评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,980评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,628评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,796评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,649评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,548评论 2 352

推荐阅读更多精彩内容