写这个作业碰到一个问题,就是开始写入文件时,文件流没有关闭,导致后来read一直为null,特此记录
# -*- coding: utf-8 -*-
# @Time : 2021/7/17 15:47
# @Author :liuw
# @File : try_catch_file.py
# @Software: PyCharm
import os
import shutil
import time
'''
作业:
1.应用文件操作的相关知识,通过python新建一个古诗.txt,选择一首古诗写入文件中
2.另外写一个函数,读取指定文件古诗.txt,将内容复制到copy.txt,并在控制台输出"复制完毕"
3.提示 分别定义2个函数,完成读文件和写文件的操作
尽可能完善代码,添加异常处理
'''
list=['床前明月光','疑是地上霜','举头望明月','低头思故乡']
project_path='C:\Users\15012\PycharmProjects\pythonProject\spider_from_bili_ITsishu\'
'''
读取指定文件,并复制到copy.txt
'''
def readFile(read_flag):
# 1、使用读写文件进行复制文件
file = open('file.txt',
'r', encoding="utf-8")
for i in range(0,4):
read_print = file.readline()
print("读取行 %s" % (read_print),end="")
time.sleep(1)
print("读取完毕")
time.sleep(1)
read_flag += 1
return read_flag
file.close()
# f2 = open(newFile, 'w')
# f2.flush()
# for str2 in f1.readlines():
# print(str2)
# f2.write(str2)
#
# f1.close()
#
# if os.path.exists('copy.txt'): #指的是当前目录
#
# print(u'文件复制成功')
#
# f2.close()
'''
将古诗中优美的词句写入到文件中
'''
def writeFile(file,list):
for str in list:
file.write(str+' ')
print('古诗写入完毕!')
time.sleep(1)
file.close() # 开始就是这里忘了关闭文件流了 对python还是不熟悉 也没有对应的报错 不像Java
def copy(copy_flag): #文件复制
f = open("file.txt","r",encoding='utf-8')
c = open("copy.txt", "w", encoding='utf-8')
lines = f.readlines()
for line in lines:
print('copy'+line,end="")
c.write(line)
f.close()
c.close()
print(" 复制完毕 ")
time.sleep(1)
copy_flag += 1
return copy_flag
if os.path.isfile(project_path+'file.txt'):
os.remove('file.txt')
try:
read_flag = 0
copy_flag = 0
file = open(project_path+'file.txt',
'a',encoding="utf-8")
writeFile(file,list)
try:
read_flag = readFile(read_flag)
if read_flag == 0:
print("读出失败")
time.sleep(1)
copy_flag = copy(copy_flag)
if copy_flag == 0:
print("复制失败")
time.sleep(1)
finally:
file.close()
print("程序执行完毕")
time.sleep(1)
except Exception as result:
print(result)
print("程序异常")
time.sleep(1)
# shutil.copyfile('file.txt', 'copy.txt')
finally:
file.close()
# def text_create(name, msg):
# # 新创建的txt文件的存放路径
# desktop_path = "C:\Users\15012\Desktop\"
#
# full_path = desktop_path + name + '.txt' # 也可以创建一个.doc的word文档
#
# file = open(full_path, 'w')
#
# file.write(msg) #msg也就是下面的Hello world!
#
# # file.close()
#
# text_create('mytxtfile', 'Hello world!')
# 调用函数创建一个名为mytxtfile的.txt文件,并向其写入Hello world!