文件操作
练习
file = open("/Users/v_baishengpo/Desktop/words.txt", "r", encoding="utf-8")
a = file.read()
print(a)
file.close()
问题答案:是不能,因为当我们再次调用read方法时,指针在文件末尾此时是读取不到内容的
file = open("/Users/v_baishengpo/Desktop/words.txt", "r", encoding="utf-8")
while True:
#读取一行的内容
text = file.readline()
#判断是否读取到内容
if not text:
break
print(text,end="")
file.close()
例子:
file1 = open("/Users/v_baishengpo/Desktop/word.txt", "w", encoding="utf-8")
"""
小文件复制
"""
#读取words内容
text = file.read()
#将读取的words内容写入word
file1.write(text)
#关闭两个文件
file1.close()
file.close()
file = open("/Users/v_baishengpo/Desktop/words.txt", "r", encoding="utf-8")
file1 = open("/Users/v_baishengpo/Desktop/word.txt", "w", encoding="utf-8")
"""
大文件复制
"""
while True:
# 读取words一行内容
text = file.readline()
#判断本行是否有内容
if not text:
break
#把本行内容写入word
file1.write(text)
#关闭两个文件
file1.close()
file.close()
注意 :如果我们打开文件的时候使用的是只写模式,此时如果我们直接关闭文件的话,会把文件里的内容全部截断
file1 = open("/Users/v_baishengpo/Desktop/word.txt", "w", encoding="utf-8")
file1.close()