小编是个编程小白,突然有一天有了学习一种语言的冲动,考虑了一下,选定了python,之后就买了本书开始了自学之旅,选定的教材是《笨方法学python》,额,这里不讨论这本教材的好坏了,反正我选了这本。
学了20课之后,突然意识到可以将我在学习中的代码分享出来,也可以增加我的学习动力。
好了不废话了,开始分享吧
# -*- coding: utf-8 -*-
#开始今天的课程,先跟着书打一段码
from sys import argv
script,input_file=argv
txt=open(input_file,"w")
line1=raw_input("line1:")
line2=raw_input("line2:")
line3=raw_input("line3:")
a=(line1,"\n",line2,"\n",line3)
txt.writelines(a)
txt.close()
#在这个地方我创建了一个.txt文档,并且通过shell输入在里面写了一点东西,这段在原书代码里是没有的
#因为原书中在shell中输入的test.txt在前面的练习中创建好了,但我在反复的练习中已将它删除,所以我需要在这创建
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()
#这里需要注意一下,只能用readline()不能用read(),因为你如果用read()文件就会被整个读完,程序很笨,只能顺序读下去,不会返回
#用read()则只会读一行,程序会接着再度下一行,当然,如果你这样输入readline(2),那每次他只会读两个字符
current_file=open(input_file)
#文件在读取的过程前,有个打开的过程,这个赋值就是执行这个过程
print "\n first let's print the world file:\n"
#此处\n的作用是为了输出时这一行和下一行文字隔开
print_all(current_file)
#代码到这,是将前面创建的.txt文件打开、读取、打印
print "\n now let's rewind,kind of like a tape:\n"
rewind(current_file)
#这里是需要文件执行seek的命令,至于seek是什么意思,底下做了测试,从63到165行
print "\n let is print three lines:\n"
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)
#这里就是将文件在读一次的过程,额,有个+号需要注意,实际上在python中是可以不断赋值的,这很正常,下面会有个关于+号的小测试
#ok写完了,开始跑一下吧
#在shell中输入python exl20.py test.txt
#跳出line1:时输入一段英文,随你怎么输,如this is line 1
#同样,跳出line2:,输入this is line 2
#同样,跳出line3:,输入this is line 3
#输出:
#first let's print the world file:
#this is line 1
#this is line 1
#this is line 1
#now let's rewind,kind of like a tape:
#let is print three lines:
#1 this is line 1
#2 this is line 1
#3 this is line 1
"""
#这是关于+号的测试
a=1
print a
b=a+1
print b
c=b+1
print c
#输出
#1
#2
#3
#预料之中的结果
"""
#下面我要做个实验。测试seek的作用
"""
b=raw_input("txt:")
c=open(b)
"""
#这算是为下面的测试创建了一个环境,比较shell需要知道打开哪个文件
"""
def y_b(f):
print c.read()
def y_b_2(f):
print c.read()
print "one:"
y_b(c)
print "two:"
y_b_2(c)
"""
#输入python exl20.py,之后输入test.txt
#输出显示one:
#this is line 1
#this is line 2
#this is line 3
#two:
#测试结果,第二次读取输入文本时无法读出
#第二次测试
"""
def y_b(f):
print c.read()
def y_b_3(f):
c.seek(0)
def y_b_2(f):
print c.read()
print "one:"
y_b(c)
y_b_3(c)
print "two:"
y_b_2(c)
"""
#输入python exl20.py,之后输入test.txt
#输出显示
#one:
#this is line 1
#this is line 2
#this is line 3
#two:
#this is line 1
#this is line 2
#this is line 3
#测试结果,第二次读取输入文本时,可以读出
#第三次测试
"""
def y_b(f):
print c.read()
def y_b_3(f):
c.seek(1)
def y_b_2(f):
print c.read()
print "one:"
y_b(c)
y_b_3(c)
print "two:"
y_b_2(c)
"""
#输入python exl20.py,之后输入test.txt
#输出显示
#one:
#this is line 1
#this is line 2
#this is line 3
#two:
#his is line 1
#this is line 2
#this is line 3
#测试结果,第二次读取输入文本时,可以读出,但最初一个t字母没读出
#结论
#经过三次测试,得出结论,文件在一次读取是,已经读到了最后一个字符,所有的内容已经读完,没有重新回头读取的能力
最后我必须说明一下,这只是我在自学中写的东西分享出来,可能会有错误,欢迎留言指导
另外,如果你也在学,并且进度在我之后,那有什么问题,也可以问我,当然我不一定会(笑哭)