笨办法学Python记录--习题15-17 开始读写文件啦

习题15 - 17

打开并读流程:

 1 from sys import argv
 2 script,filename = argv
 3 txt = open(filename)
 4 print "Here's your file %r:" % filename
 5 print txt.read()
 6 txt.close()

对文件操作有用的方法:

close – 关闭文件。跟你编辑器的文件-> 保存.. 一个意思。

• read – 读取文件内容。你可以把结果赋给一个变量。
• readline – 读取文本文件中的一行。
• truncate – 清空文件,请小心使用该命令。
• write(stuff) – 将stuff 写入文件。                                                                                                 

写了两个小练习,问题记录:target.read()需要加上print才可以打印出来;target.write(line1+' '+line2+' ')方式能把每行line逐一输出;文件读写完毕后要close!

这个小程序有用,作用是将一个文件copy到另外一个文件中。亮点:len(xx)获取变量中内容的长度;print "Does the output file exist? %r" % exists(to_file)

 1 #将一个文件copy到另外一份文件中
 2 from sys import argv
 3 from os.path import exists
 4 
 5 script, from_file, to_file = argv
 6 
 7 print "Copying from %s to %s" % (from_file,to_file)
 8 
 9 input = open(from_file)
10 
11 indata = input.read()
12 
13 print "The input file is %d bytes long" % len(indata) #len(indata) 求长度的函数
14 
15 print "Does the output file exist? %r" % exists(to_file) #如果为TRUE,则覆盖;如果为False,则新建一个
16 print "Ready, hit RETURN to continue,ctrl-c to abort.",raw_input()
17 
18 output = open(to_file, 'w') #必须开启写权限
19 output.write(indata)         #把input内容写进去
20 print "Alright, all done"
21 
22 output.close()
23 
24 # to double check output
25 output1 = open(to_file)
26 print output1.read()
27 output1.close()
28 input.close()
原文地址:https://www.cnblogs.com/ianthe/p/3663116.html