#!/usr/bin/env python # coding: utf-8 # # Table of Contents #

1  files and dir
2  dirでのやり取り
2.1  cwd
2.2  mkdir, cd, ls
2.3  globでfull_pathで表示
3  fileの読み書き
3.1  単純な読み書き
3.2  sprintfからの出力
# # files and dir # dataなどのfileとのやり取りに関するまとめです. # # dirでのやり取り # ## cwd # In[10]: import os cwd = os.getcwd() cwd # ## mkdir, cd, ls # In[12]: new_dir = 'test_dir' os.mkdir(new_dir) os.chdir(new_dir) os.getcwd() os.listdir() # ## globでfull_path表示 # In[15]: import glob files = glob.glob(cwd+'/'+ new_dir+'/*') for file in files: print(file) # # fileの読み書き # In[16]: os.getcwd() # ## 単純な読み書き # In[17]: data = ['x', 'y'] text = "\n".join(data) with open("tmp.txt", "w") as f: f.write(text) # In[18]: with open("tmp.txt", "r") as f: lines = f.readlines() print(lines) # In[19]: for line in lines: print(line.rstrip()) # ## sprintfからの出力 # In[20]: data = [['x', 0, 'y', 0], ['x', 1, 'y', 1]] with open("tmp.txt", "w") as f: for dd in data: print(dd) string = '%4s:%3d, %4s:%3d\n' % tuple(dd) print(string) f.writelines(string) # In[21]: data = [['x', 0, 'y', 0], ['x', 1, 'y', 1]] f = open("tmp.txt", "w") for dd in data: print(dd) string = '%4s:%3d, %4s:%3d\n' % tuple(dd) print(string) f.writelines(string) f.close() # In[22]: file = open("tmp.txt", "r") lines = file.readlines() for line in lines: print(line.rstrip()) # In[ ]: