程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

笨方法学python,Lesson15,16,17

发布于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黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

12 0
收藏该文
已收藏

评论内容:(最多支持255个字符)