2018년 9월 16일 일요일

[python] 파일입출력

# 파일 입출력

file = open("test.txt", "w")
file.write('hello')
file.write("\n")
file.write('world')
file.write("\n")
file.close()

file=open("test.txt", "r")
lines = file.read()
file.close()
print(lines)

#
msg = ["HELLO\n", "WORLD\n", "안녕\n"]
file = open("test.txt", "w", encoding='utf-8')
file.writelines(msg)
file.close()

file = open("test.txt", "r", encoding='utf-8')
line = file.readline()
while line != '':
    print(line, end='')
    line = file.readline()
file.close()

print()
file = open("test.txt", "r", encoding='utf-8')
lines = file.readlines()
file.close()
line = ''
for line in lines:
    print(line, end='')
   

# list 저장
#
import csv
f=open('a.csv', 'w',newline='')
writer=csv.writer(f, delimiter=',')
writer.writerow([1,2,3])
writer.writerow([4,5,6])
f.close()

#
# list 읽기; 읽어들인 결과는 문자
#
import csv
f=open('a.csv', 'r', encoding='utf-8')
reader=csv.reader(f)
for line in reader:
    print(line)
f.close()

#
# 읽어들일 타입지정:
#
print()
import numpy as np
data = np.loadtxt('a.csv', delimiter=',', dtype=np.int32) #np.float32
print(data)

-----
참고
-----
a=[1,2,3,4,5,6]
for i in range(len(a)-1):
    print(a[i],",",end="")
print(a[len(a)-1])

python a.py > a.txt
python a.py >> a.txt

#
#
#
a=[]
for i in range(3):
    b = input()
    a.append(b)
print(a)
#다음과 같이 키보드에서 입력
1
2
3
>>>['1', '2', '3']

----- a.txt -----
1
2
3
----------------
python a.py < a.txt
>>>['1', '2', '3']

[python] 넘파이예제

print("# 1 #")
data = (11, 9, 6, 14)
n = len(data)
for i in range(n):
    print(data[i])

#
print()
print("# 2 #")
s = sum(data)
print("sum={0}".format(s))

#
print("\n# 3 #")
print("data = ( ", end="")
for i in range(n):
    print(data[i], end=" ")
print(")")

#
print("\n# 4 #")
for i in range(n):
    if (i==0):
         print("data=( %d"%(data[0]), end="")
    else:
        print(", %d"%(data[i]), end="")
print(" )")

#
print("\n# 5 #")
for freq in data:
  s += freq
print("sum={0}".format(s))
print()

#
print("\n# 6 #")
print("sum=%d"%(s))
print("sum=%5d"%(s))
print("sum=%-5d*"%(s))
print("sum=%05d"%(s))
print("sum=%05d %5.2f"%(s, s))
print("sum=%05d %6.2f"%(s, s))

#
print("\n# 7 #")
def show(list):
    n = len(list)
    for v in list:
        print(v, end=" ")
    print()
 
relativeFreq=[]
for freq in data:
    relativeFreq.append(freq / s)
 
show(relativeFreq)

# initialize list
print("\n# 8 #")
lst = [0 for _ in range(10)]
lst = [0]*10
show(lst)

#
a = np.array([])
a = np.resize(a, 10)
a.size '10
a.shape '(10,)

#
a = np.arange(0, 3)
'a=[0,1,2]

# relative frequency
print("\n# 9 #")
relativeFreq = [0]*len(data)
for idx, freq in enumerate(data):
    relativeFreq[idx] = freq / s
show(relativeFreq)

# label
print("\n# 10 #")
label = ['A', 'B', 'C', 'D']
for idx in range(len(data)):
   print("%1c\t%2d\t%1.3f" %(label[idx], data[idx], relativeFreq[idx]))

# numpy
print("\n# 11 #")
import numpy as np
ndata = np.array([11, 9, 6, 14])
s = ndata.sum()
relativeFreq = [ freq / s for freq in ndata]
for idx in range(ndata.size):
   print("%1c\t%2d\t%1.3f\t%2.2f%%" %(label[idx], ndata[idx], relativeFreq[idx], relativeFreq[idx]*100.0))


# * graph
print("\n# 12 #")
HEIGHT = 10
star = np.array([f * HEIGHT for f in relativeFreq])
show(star)
star = star.round()
star = star.astype(np.int32)
show(star)

space = [HEIGHT-s for s in star]
show(space)

for i in range(HEIGHT):
    c = [i < s for s in space]
    print(c)
    c = [' ' if c[idx]==True else '*' for idx in range(len(star))]
    print(c)


#
print("\n# 13 #") 
for i in range(HEIGHT):
    c = [i < s for s in space]
    c = [' ' if c[idx]==True else '*' for idx in range(len(star))]
    print(c)

 
#
print("\n# 14 #") 
for i in range(HEIGHT):
    c = [i < s for s in space]
    c = [' ' if c[idx]==True else '*' for idx in range(len(star))]
    for j in range(len(star)):
        print("%c "%c[j], end="")
    print()
 
 
# remove empty line
print("\n# 15 #") 
for i in range(HEIGHT):
    c = [i < s for s in space]
    c = [' ' if c[idx]==True else '*' for idx in range(len(star))]
    d = all([c[idx]==' ' for idx in range(len(star))])
    if (d==False):
        for j in range(len(star)):
            print("%c "%c[j], end="")
        print()
 
     
 # another example
print("\n# 16 #")
label = ['seoul', 'pusan', 'daegu', 'incheon', 'kwangju', 'daejeon', 'ulsan']
ndata = np.array([5087, 1639, 1180, 1350, 664, 726, 544])
sum = ndata.sum()
rf = [f/sum for f in ndata]
for idx in range(ndata.size):
  print("%10s\t%2d\t%1.3f\t%2.2f%%" %(label[idx], ndata[idx], rf[idx], rf[idx]*100))
print()
H = 20
star = np.array([f * H for f in rf])
star = star.round()
star = star.astype(np.int32)
star = [H-s for s in star]
for i in range(H):
  c = [' ' if i < s else '*' for s in star]
  d = all([c[idx]==' ' for idx in range(ndata.size)])
  if (d == False):
      for j in range(ndata.size):
          print("%c" %c[j], end='')
      print()
   
   
 # pyplot
print("\n# 17 #")
import matplotlib.pyplot as plt
plt.plot(rf)
plt.bar(range(ndata.size), rf)
plt.xticks(range(ndata.size), label)
plt.show()

# data set -> relative freq., cumulative relative freq. table, histogram
# read data from file, data.csv
# pyplot: http://bcho.tistory.com/m/1201 pyplot 사용법
# numpy: http://taewan.kim/post/numpy_cheat_sheet/