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

论坛 期权论坛 脚本     
匿名技术用户   2021-1-2 06:58   41   0

这是基本的文件操作示例,是《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()


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP