发布于2019-09-03 12:59 阅读(855) 评论(0) 点赞(12) 收藏(0)
Exercise 15
代码
from sys import argv
script, filename = argv
txt = open(filename)
print "Here is your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
输出
Notes:
①查看python文档,python提示打开文件的首选方法是open(name[,mode[,buffering]])函数
②文件对象.read()方法读取文件内容,有一个可选参数选择读取的长度,语法为file.read([size])
③在python的交互模式中打开文件,需输入文件的完整目录
>>> txt = open("E:\\code\\LPTHW\\ex15_sample.txt")
>>> print txt.read()
One
Two
Three
④文件对象.close()用于保存并关闭文件,在对文件操作完成后关闭文件
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)."
print "If you do want that, hit RETURN."
raw_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 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")
line3 = raw_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()
输出
Notes:
①文件对象.truncate()方法会清除文件内容
②write()方法把括号中的字符串对象写入文件中,字符串对象支持格式化及转义操作
③open()打开模式'w'表示也写的方式打开,文件不存在会被创建,已存在会在打开时清空内容。不添加打开参数时,open()默认以只读的方式打开文件
Exercise 17
代码
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file,to_file)
# we could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
out_file = open(to_file,"w")
out_file.write(indata)
print "Alright, all done."
out_file.close()
in_file.close()
输出
Notes:
①os.path模块中的exists()函数用来判断一个文件是否存在,存在返回True,否则返回False
作者:高富帅
链接:https://www.pythonheidong.com/blog/article/85002/d7ca069fae7ef68f8bdb/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!