您的位置:首页 > 编程语言 > Python开发

Python文件读写+创建临时文件夹的基本方法

2017-02-27 19:41 906 查看
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os

def makeTempDir():
"""
设定缓存目录,为当前文件夹的temp文件夹
如果没有对应文件夹则创建文件夹
:return: temp_pwd
"""
temp_pwd = os.path.join(os.getcwd(), 'temp') # 文件缓存目录为当前文件夹下的temp文件夹
if os.path.exists(temp_pwd) == False:
os.makedirs(temp_pwd)
return temp_pwd

def test():
temp_pwd = makeTempDir()
with open(os.path.join(temp_pwd,'test.txt'), 'w') as f: #写文件,没有文件则会创建
for i in range(10):
f.write("python\n")

with open(os.path.join(temp_pwd,'test.txt'), 'r') as f:
lines = f.readlines() #一次性读所有的行
print lines
for line in lines[5:]: #只处理读出来的后5行
line = line.strip('\n')
print line

def main():
test()

if __name__ == '__main__':
main()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: