File operations in Python

Read

#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()

writing

Overwrite (not additional)

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()

Postscript

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()

Other

check existence

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

Delete file

#coding:utf-8

import os

os.remove('test.txt')

Recursively delete non-empty directories

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

File operations in Python
File operations in Python
ORC, Parquet file operations in Python
[Python] File / directory operations
File processing in Python
Summary of python file operations
Four arithmetic operations in python
Download the file in Python
Wrapping git operations in Python
File operations
File / folder path manipulation in Python
Perform Scala-like collection operations in Python
Save the binary file in Python
Linebot creation & file sharing in Python
Create a binary file in Python
Python memo ① Folder and file operations
Quadtree in Python --2
Python in optimization
CURL in python
Script python file
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
Python file processing
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python