#coding:utf-8
f = open('test.txt','r')
for row in f:
print row.strip()
f.close()
If you use with as shown below, you will never forget close ().
with open('test.txt','r') as f:
for row in f:
print row.strip()
If the file does not exist, it will be newly created.
#coding:utf-8
f = open('test.txt','w')
f.write('hoge\n')
f.close()
If the file does not exist, it will be newly created.
#coding:utf-8
f = open('test.txt','a')
f.write('hoge\n')
f.close()
The file system uses os.path. If you use exists (), you can check the existence regardless of the folder or file.
#coding:utf-8
import os.path
if os.path.exists('test.log'):
print u"Existence."
else:
print u"Non-existent"
If negative, use if not os.path.exists ('test.log') :.
Delete file
#coding:utf-8
import os
os.remove('test.txt')
It seems that non-empty directories cannot be deleted recursively if it is an os system, so shutil is used.
#coding:utf-8
import shutil
shutil.rmtree('data')
Recommended Posts