《 笨方法学 Python 》_ 习题 15 - 17

习题 15:读取文件

这个习题涉及写两个文件,一个是 ex15.py 文件,另外一个是 ex15_sample.txt,是供你的脚本读取的文本文件。下面是该文

本文件的内容。

This is stuff I typed into a file.

It is really cool stuff.

Lots and lots of fun to have in here.

from sys import argv

script, filename = argv

txt = open(filename)

print("Here's your file %r:" % filename)
print(txt.read(), '\n')

print("Type the filename again:")
file_again = input("> ")

txt_again = open(file_again)

print(txt_again.read())

txt.close()
txt_again.close()        # 处理完文件后需要将其关闭

习题 _ 16:读写文件

常用命令:

        close           关闭文件,跟编辑器的“文件” → “保存”是一个意思
        read            读取文件内容,可以把结果赋给一个变量
        readline        读取文本文件中的一行
        truncate        清空文件
        write(stuff)    将 stuff 写入文件

write 需要接受一个字符串作为参数,从而将该字符串写入文件。

from sys import argv

script, filename = argv

print("We're going to erase %r." % filename)
print("If you do't want that, hit CTRL-C(ˇC)")
print("If you do want that, hit RETURN")

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 = input("line 1:")
line2 = input("line 2:")
line3 = 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()


如果用了 'w' 参数,truncate() 是必需的吗?

不是必需的,'w' 会将原有内容自动清空,进行写入,所以手动清空不是必需的。


习题 17:更多文件操作

将一个文件中的内容复制到另外一个文件中。

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print("Coping from %s to %s." % (from_file, to_file))

# we could do these two on one line too, how?
in_file = open(from_file)
indata = in_file.read()        # indata = open(from_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.")
input()

out_file = open(to_file, 'w')
out_file.write(indata)

print("Alright, all done")

out_file.close()
in_file.close()
运行该脚本需要两个参数:一个是待复制的文件,另一个是要复制到的文件,使用上个习题的 ex16_sample.txt 作为待复制的文件。



exists 将文件名字符串作为参数,如果文件存在的话,它将返回 True;否则将返回False。

len() 会以数的形式返回你传递的字符串的长度。

猜你喜欢

转载自blog.csdn.net/yz19930510/article/details/80537565