小白学Python(二) 基本文件操作

来源:互联网 发布:ansys15.0软件 编辑:程序博客网 时间:2024/05/22 06:57

这是基本的文件操作示例,是《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 osls = os.linesep#get file namewhile 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 linesall = []print("\nEnter lines ('.' by itself to quit).\n")while True:line = input('>')if line == '.':breakelse:all.append(line)#write to filewfile = open(fname, 'w')for each in all:wfile.write(each + ls)wfile.close()print("DONE!")


二、编写程序打开文件并将内容打印至屏幕

"""Display text file"""import osfname = input("Please input the file name\n>")with open(fname, 'r') as rfile:for each_line in rfile:print(each_line)rfile.close()


0 0