《笨方法学 Python 3》16.读写文件

Zed想要我们记住的命令:

  • close():关闭文件,这个很重要,处理完文件要进行关闭,如果不关闭是无法保存的;
  • read():读取文件内容,你可以把读取的内容赋值给一个变量;
  • readline():只读取文本文件中的一行;
  • truncate():清空文件,谨慎使用;
  • write('stuff '):把stuff写入文件,注意带引号;
  • seek(0):将读写位置移动到开头;

下面是我网上看到的:

打开文件

  • open('filename','r')     # 读模式,默认模式;
  • open('filename','w')   # 写模式
  • 注意,注意,注意:‘w’模式在写入时会自动清空原有内容!!!所以练习题里第15行代码就不需要了
  • open('filename','a')   # 追加模式
  • 修饰符+,可以用来实现'w+'、'r+'、'a+',这样可以把文件同时以读写的方法打开,并根据使用的字符,以不一样的方式实现稳健的定位!

注:rb 是以二进制读取,现在你觉得没用对吧,我也这么觉得...

but 在以后用到socket的时候,传输文件,读取和写入用的都是二进制形式

rb和wb可以更快速的进行文件的传输

读取文件

  • read()                       # 一次读取整个文件,文件大不适用
  • readline()                 # 一次只读取一行,占内存小,速度慢
  • readlines()               # 一次性读取,将内容分析成一个行的列表,可以由for...in...处理

写入文件

  • write(content)           # 不会换行哦
  • writeline(content)     # 下次会写在下一行

基础练习: 

from sys import argv

script, filename = argv

print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, 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()

注意:写入的话要用open(filename,'w')方法,后面加上'w',就像第12行那样;

结果:

终端显示

 检查下当前的文件夹里是不是有个test.txt文件?内容是不是你输入的那样?

 


折腾一下: 

1.继续接代码,把刚刚写入的内容读取并打印出来

2.优化代码,把write()的6行代码写成1行

from sys import argv

script, filename = argv

print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, 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(f"{line1}\n{line2}\n{line3}\n")

print("And finally, we read it and print it.")

target = open(filename)
print(target.read())

target.close()

 

OK,完成。

其实我刚开始是想这样写的

我感觉这样应该没问题,但是报错了:大概意思是,无法读取

然后我又把上面第12行改了一下,改成这样

还是不行,报错了,所以就改成了刚开始的那样子!

END!!! 

猜你喜欢

转载自blog.csdn.net/waitan2018/article/details/82355150