LoginSignup
6
5

More than 3 years have passed since last update.

ディレクトリ&ファイル操作@python

Last updated at Posted at 2018-07-15

ファイルの存在確認


#python3
import os                                #osを読み込む
cwd = os.getcwd()                        #現在のワーキングディレクトリを取得
cwd_f = cwd + "/"+filename               #ファイル名を含めたディレクトリを作成 
if os.path.isfile(cwd_f) == True         #そのファイルが存在するか確認
   ...   

ファイルを開き,編集する


f = open(filename,'w')    #ファイルを開くが,中身を切り詰める
#f = open(filename,'a')   #ファイルの末尾にデータを追記(addition)するモード
f.write(INPUT)            #書き込みたいINPUTを書き込む(‘w’,’a’の時に操作可)
f.close                   #これが必要.

ちなみにファイルの読み取りだけだと...


f = open(filename,'r')    #読取用にファイルを開く
T = f.read()              #全ファイル読取[2]    
f.close

with open(filename,r) as fr:
     fr.read()            #この形式だとf.close不要[1]


#繰り返しの読み込み[1]
with open('mydata.txt') as file:           #fileというクラスで読み込む
    for line in iter(file.readline, ''):   #""(空文字列)が来るまでforループを回す
    T = file.readline()                    #行ずつに読む

ディレクトリを変える


#python 3
import os

os.chdir('Sample')  
  #相対パスを用いたディレクトリ移動
  #現在のディレクトリにあるSampleというフォルダに移動
os.chdir('../') 
  #相対パス.一つ上の階層のディレクトリへ移動
os.chdir('../../')
  #相対パス.二つ上の階層へ移動.

参考
[1] Python3.6ドキュメント: 組み込み関数
[2] Python3.6ドキュメント: ストリームを扱うコアコンテンツ

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5