《笨办法学python》(第四版)笔记 - day3

习题15:读取文件

笔记:
file = open(filename):打开文件filename,并赋值给file。
file.read():file执行你的read命令吧,无需任何参数。
file.close():处理完文件后需要将其关闭,这一点很重要。
代码:

from sys import argv #从sys这个module导入argv这个包


print("这个例子是想打开一个文件夹并读出文件内容。")


script = argv #使用argv来获取文件名

filename = input("请输入要打开的文件名:> ")


txt = open(filename) #打开名为filename的文件夹



print("Here's your file %r:" % filename) #输出一句话,其中filename是刚刚获取到的argv该文件夹的名字

print(txt.read()) #读出文件filename里的内容

txt.close() #file.close()关闭文件。关闭后文件不能再进行读写操作。


print("Type the filename again:") #再次打印文件的内容

file_again = input("> ") #将要打开的文件名输入并传递给file_again变量

txt_again = open(file_again) #open打开文件

print(txt_again.read()) #read()读取文件内容
txt_again.close()

习题16:读写文件

笔记:
close – 关闭文件。跟你编辑器的 文件->保存… 一个意思。
read – 读取文件内容。你可以把结果赋给一个变量。
readline – 读取文本文件中的一行。
truncate – 清空文件,请小心使用该命令。
write(stuff) – 将stuff写入文件。接收一个字符串作为参数,从而将该字符串写入文件。
代码:

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 don 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+"\n"+line2+"\n"+line3+"\n")

print("And finally, we close it.")

习题17:更多文件操作

笔记:
input = open(from_file)
indata = input.read() #读出输入数据
output = open(to_file, ‘w’) #打开目标文件
output.write(indata) #将文件1内容写入文件2

代码: 编写一个Python脚本,将一个文件中的内容拷贝到另一个文件中。

from sys import argv #导入这个argv,也就是本脚本文件的文件名
from os.path import exists #将文件名字符串作为参数,如果文件存在则返回True,否则返回FFalse。

script, from_file, to_file = argv #将argv赋值给script
print("Copying from %s to %s" %(from_file, to_file))

input = open(from_file)
indata = input.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.") #文字提示:开始拷贝文件

output = open(to_file, 'w') #打开目标文件
output.write(indata) #将文件1内容写入文件2
print("Alright, all done.") #拷贝完成文字提示

output.close() #关闭输出文件

问题: 为什么要在代码中写output.close()?
答:
close() 方法用于关闭一个已打开的文件。关闭后的文件不能再进行读写操作, 否则会触发 ValueError 错误。 close() 方法允许调用多次。
当 file 对象,被引用到操作另外一个文件时,Python 会自动关闭之前的 file 对象。 使用 close() 方法关闭文件是一个好的习惯。
正解: 如果没有close(),写入的内容可能会存在缓冲区中,并没有真正的写入文件里。

发布了13 篇原创文章 · 获赞 1 · 访问量 632

猜你喜欢

转载自blog.csdn.net/weixin_43136158/article/details/104812098