python求15 17 23 65 97的因数_笨方法学python,Lesson15,16,17

本文详细介绍了Python中文件操作的三个练习,包括读取文件内容、清空并写入新内容以及复制文件。通过示例代码展示了如何使用open()函数、read()、write()、truncate()等方法进行文件操作,并强调了文件关闭的重要性。
摘要由CSDN通过智能技术生成

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()

输出

22f807fdcf6b1ffcbbc03f7a1de0f107.png

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()

输出

28e669cc84dec90b55fc136d05b8dad8.png

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()

输出

75ee0bfe6d05ca1ba03378d9763a29c2.png

Notes:

①os.path模块中的exists()函数用来判断一个文件是否存在,存在返回True,否则返回False

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值