>
: 출력될 내용이 .txt 파일로 저장
>>
: 기존에 있던 파일의 내용에 출력될 내용 추가
a = a[1, 2, 3, 4, 5, 6]
for i in range(len(a)-1):
print(a[i], ",", end="")
print(a[len(a)-1])
C:\>python a.py
1, 2, 3, 4, 5, 6
C:\>python a.py > a.txt
C:\>type a.txt
1, 2, 3, 4, 5, 6
C:\>python a.py >> a.txt
1, 2, 3, 4, 5, 6
1, 2, 3, 4, 5, 6
<
: 키보드 력
a = []
for i in range(3):
b = input()
a.append(b)
print(a)
C:\>python a.py
1 // 키보드 입력
2
3
['1', '2', '3']
C:\>echo 1 > a.txt
C:\>echo 2 > a.txt
C:\>echo 3 > a.txt
C:\>type a.txt
1
2
3
C:\>python a.py < a.txt // 키보드 입력 대체
['1', '2', '3']
a = 'Hello'
f = open('a.txt', 'w') # 파일을 'w':쓰기모드로
f.write(a)
f.write('\n')
f.write(a)
f.close()
[결과]
C:\>python a.py
C:\>type a.txt
Hello
Hello
C:\>
a = 1
f = open('a.txt', 'w')
f.write(a)
f.write('\n')
f.write(a)
f.close()
[결과]
C:\>python a.py
에러 발생
-> 파일은 기본적으로 문자열만 다룬다
C:\>echo 1 > a.text
C:\>type a.txt
1
>>> f = open('a.txt', 'r')
>>> line = f.read()
'1\n'
>>>f.close()
# 다 문자로 읽어 들인다
# input() 함수와 비슷하다. 키보드에서 1을 누르면 '1'을 남긴다.
# 유닉스라는 운영체제에서는 키보드도 파일로 다룬다.
read()
: 파일에 있는 전체를 읽는다>>> f = open('a.txt', 'r')
>>> data = f.read()
'Hello\nHello'
>>> f.close()
>>> print(data)
Hello
Hello
readline()
: 파일에 있는 것을 한 줄씩 읽는다>>> f = open('a.txt', 'r')
>>> line = f.readline()
'Hello\n'
>>> line = f.readline()
'Hello'
>>> f.close()
>>> f = open('a.txt', 'r')
>>> line = f.readline()
>>> while(line != ''):
... print(line)
... line = f.readline()
>>> f.close
# 공백이 아닌 동안 계속 한 줄씩 읽는다.
>>> f = open('a.txt', 'w')
>>> f.writelines('Hello')
>>> f.close()
>>> f = open('a.txt', 'a')
>>> f.writelines('World')
>>> f.close()
>>> f.writelines(['Hello', 'World'])
C:\> type a.txt
HelloWorld
-readlines
는 리스트를 담긴다
>>> f = open ('a.text', 'r')
>>> lines = f.readlines()
['Hello\n', 'Hello']
>>> f.close
lines = f.writelines(['Hello', 'World'])
cvs
사용Import cvs
F = open('a.txt', 'w')
w = cvs.writer(F)
w.writerow([123])
f.close()
>>> f = open('a.text', 'r')
>>> lines = f.read()
>>> f.close()
>>> lines
'1234\n\n'
try
블록에서 예외 상황이 발생하면 exept
블록을 수행한다try:
f = open('k.txt', 'r')
contents = f.read()
f.close()
print(contents)
except:
print('File Not Found')
def isFile(file):
try:
f = open(file, 'r')
f.close()
return True
except:
return False
isFile('a.txt')
N = 2000
areaSquare = N
areaCircle = 0
for i in range(N):
x = random.random()
y = random.random()
r = (x - 0.5)*(x - 0.5)+(y - 0.5)*(y - 0.5)
bInCircle = True if r<=0.25 else False
if bInCircle:
areaCircle += 1
pi = 4 * areaCircle / areaSquare
print(pi)
import random
def approximatePi(n):
areaSquare = n
areaCircle = 0
for i in range(n):
x = random.random()
y = random.random()
r = (x - 0.5)*(x - 0.5)+(y - 0.5)*(y - 0.5)
bInCircle = True if r<=0.25 else False
if bInCircle:
areaCircle += 1
pi = 4 * areaCircle / areaSquare
print(pi)
for n in range(10000, 1000000, 100000):
pi = approximatePi(n)
print(n, pi)
import random
def approximatePi(n):
areaSquare = n
areaCircle = 0
f = open('a.csv', 'w') # 엑셀로 읽힌다
for i in range(n):
x = random.random()
y = random.random()
r = (x - 0.5)*(x - 0.5)+(y - 0.5)*(y - 0.5)
bInCircle = True if r<=0.25 else False
if bInCircle:
areaCircle += 1
pos = '{}, {}\n'.format(x, y)
f.write(pos)
pi = 4 * areaCircle / areaSquare
f.close()
return pi
pi = approximatePi(10000)
print(pi)
C:\>pip install matplotlib
import random
import matplotlib.pyplot as plt
def approximatePi(n):
areaSquare = n
areaCircle = 0
ptX = []; ptY = []
#f = open('a.csv', 'w')
for i in range(n):
x = random.random()
y = random.random()
r = (x - 0.5)*(x - 0.5)+(y - 0.5)*(y - 0.5)
bInCircle = True if r<=0.25 else False
if bInCircle:
pos = '{}, {}\n'.format(x, y)
ptX.append(x)
ptY.append(y)
#f.write(pos)
pi = 4 * areaCircle / areaSquare
#f.close()
plt.scatter(ptX, ptY)
plt.savefig('a.png')
plt.show()
return pi
pi = approximatePi(10000)
print(pi)
plt.scatter(ptX, ptY)
: 분산형 그래프 그리는 함수
plt.savefig('a.png')
: 그림으로 저장하는 함수
plt.show()
: 화면상에 출력하는 함수
import os
class PhoneBook():
def --init--(self):
self.phoneBook={}
self.filename='phonebook.txt'
def isEmpty(self):
if n==0:
return True
else:
return False
def load(self):
if os.path.isfile(self.filename)==False:
print(self.filename, 'Not Found')
return
f = open(self.filename, 'r')
lines = f.readlines()
f.close()
self.phoneBook.clear()
for record in lines:
record = record.split(',')
name = record[0].strip()
phone = record[1].strip()
self.phoneBook[name] = phone
print(len(lines), 'records loaded')
def save(self):
if self.isEmpth():
print('Empty')
return
f = open(self.filename, 'w')
for item in self.phoneBook.items():
record = '{},{}\n'.format(item[0], item[1])
f.write(record)
f.close()
print(len(self.phoneBook), 'record saved')
def Main():
myPhoneBook = PhoneBook()
print('\nstarting...')
myPhoneBook.load()
bFinish = False
while not bFinish:
print('\n---------------')
print('[F] Find')
print('[N] Insert')
print('[U] Update')
print('[D] Delete')
print('[A] List All')
print('[L] Load')
print('[S] Save')
print('[Q] Quit')
print('\n---------------')
menuList = ['F', ]