dataなどのfileとのやり取りに関するまとめです.
import os
cwd = os.getcwd()
cwd
'/Users/bob/python/doing_math_with_python/symbolic_math'
new_dir = 'test_dir'
os.mkdir(new_dir)
os.chdir(new_dir)
os.getcwd()
os.listdir()
[]
import glob
files = glob.glob(cwd+'/'+ new_dir+'/*')
for file in files:
print(file)
os.getcwd()
'/Users/bob/python/doing_math_with_python/symbolic_math/test_dir'
data = ['x', 'y']
text = "\n".join(data)
with open("tmp.txt", "w") as f:
f.write(text)
with open("tmp.txt", "r") as f:
lines = f.readlines()
print(lines)
['x\n', 'y']
for line in lines:
print(line.rstrip())
x y
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)
['x', 0, 'y', 0] x: 0, y: 0 ['x', 1, 'y', 1] x: 1, y: 1
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()
['x', 0, 'y', 0] x: 0, y: 0 ['x', 1, 'y', 1] x: 1, y: 1
file = open("tmp.txt", "r")
lines = file.readlines()
for line in lines:
print(line.rstrip())
x: 0, y: 0 x: 1, y: 1