一个简单的python读写文件脚本
- 作者: 妈常说我妈最帅
- 来源: 51数据库
- 2022-08-12
#!/usr/bin/env python
'makeFile.py -- create a file'
import os
ls = os.linesep
# get filename
while True:
fname = raw_input('Input an unused file name >')
if os.path.exists(fname):
print "ERROR: '%s' already exists" %fname
else:
break
# get file content lines
all = []
print "\nEnter lines (input '.' to quit).\n"
# loop until user terminates input
while True:
entry = raw_input('>')
if entry == '.':
break
else:
all.append(entry)
# write lines to file with proper line-ending
fobj = open(fname, 'w')
fobj.writelines(['%s%s' %(x, ls) for x in all])
fobj.close()
print 'DONE'
if __name__ == '__main__':
print 'innter module'
上面的代码用来创建一个新文件并写入文本,第6行给os模块中的linesep起了给别名ls,这样做的好处一方面简化了长长的变量名,另一方面也是主要原因用于提高代码性能,因为访问这个变量时首先要检测os模块,然后再解析linesep,linesep是行结束符标志,linux下是'\r',windows下是'\r\n',用本地变量保存更好。第34行使用了__name__,这主要用于代码内测试,它的值是__main__,但python文件通常作为模块被其它文件import,这时__name__的值是这个模块名,就不会执行模块内的测试代码了。
#!/usr/bin/env python
'readFile.py -- read and display file'
# get filename
fname = raw_input('Enter filename >')
print
# attempt to open file for reading
try:
fobj = open(fname, 'r')
except IOError, e:
print "***** file open error:", e
else:
# display contents to the screen
for eachLine in fobj:
print eachLine,
fobj.close()
上面的代码用来读文件并显示其内容到屏幕上,使用了try-except-else异常处理机制。
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
