Python 文件的读取写入
# 写入文件
def createFile(file_Path, option, conten):
try:
f = open(file_Path, option)
try:
print(conten, file=f)
finally:
f.close()
print("文件关闭")
finally:
print("操作完成!")
# 读取文件
def readFile(file_Path, options):
try:
f = open(file_Path, options)
try:
while True:
content = f.readline()
if len(content) == 0:
break
print(content, end='')
createFile("copy.txt", "w", content)
finally:
f.close()
print("文件关闭!")
finally:
print("读取完毕!")
contents = '''九顶几重山?层峦落日边。入云三千丈,金身塑巉岩。聚灵开天象,幻化宫阙烟。绝岸听涛冷,江出万谷寒。'''
createFile("gushi.txt", "w", contents)
readFile("gushi.txt", "r")
结果
|