这是基本的文件操作示例,是《Python核心编程》上的样例程序对Python3.4的适配版,如有不足请诸君斧正
一、编写程序创建新文件并向文件内写入内容
"""makeTextFile.py use this to create a new file"""
"""You need to open the file with notepad to check the line break"""
import os
ls = os.linesep
#get file name
while True:
fname = input("\nPlease input the file name:\n>")
if os.path.exists(fname):
print("ERROR: " + '%s' %fname + " already existes")
else:
break
#get file content lines
all = []
print("\nEnter lines ('.' by itself to quit).\n")
while True:
line = input('>')
if line == '.':
break
else:
all.append(line)
#write to file
wfile = open(fname, 'w')
for each in all:
wfile.write(each + ls)
wfile.close()
print("DONE!")
二、编写程序打开文件并将内容打印至屏幕
"""Display text file"""
import os
fname = input("Please input the file name\n>")
with open(fname, 'r') as rfile:
for each_line in rfile:
print(each_line)
rfile.close()