Python 文件操作

打开文件

 

创建一个文件,Python中内建open()函数。

open(file,mode='r')
#file为文件名路径(绝对或相对于当前工作目录)
#mode参数默认为'r'只读,'w'写入模式 'x'如果文件存在则打开失败 'a'在已有文件末尾追加 'b'二进制文件模式 't'文本文件模式(默认)'+'读写(更新)
f = open('/test.txt', 'w')
print(f.name)
f.close()  #关闭文件

 

删除文件

删除文件需调用os模块,先确认文件是否存在

import os

f = open('/test.txt', 'w')
print(f.name)
f.close()
if os.path.exists(f.name):
    os.remove(f.name)
    print(f'{f.name} deleted.')
else:
    print(f'{f.name} does not exist.')

  

读写文件

 创建完文件之后可以用f.write()写入数据与f.read()读取数据

f = opren('/test.txt', 'w')
f.write('first\nsecond\nthird\n')
f.close()

f = open('/test.txt', 'r')
s = f.read()
print(s)
f.close()

  

 with 语句块

针对文件操作,Python有语句块写法,

  with open(...) as f:

    f.write(…)

    …

这样可以针对当前特定模式打开的某个文件的各种操作都写入同一语句块(用with语句块就不用加file.close() )

import os

with open('/test-file.txt', 'w') as f:
    f.write('first line\nsecond line\nthird line\n')
    
with open('/test-file.txt', 'r') as f:
    for line in f.readlines():
        print(line)

if os.path.exists(f.name):
    os.remove(f.name)
    print(f'{f.name} deleted.')
else:
    print(f'{f.name} does not exist.') 
>>>first line

>>>second line

>>>third line

>>>test-file.txt deleted.

 

posted @ 2019-07-08 15:20  REDgreen  阅读(260)  评论(0)    收藏  举报