반응형

/*******************************************************************************************************************

-- Title : [Py3.4] Text 파일 입출력
-- Reference : itsdong.com
-- Key word : text txt 텍스트 file input readline read line write readlines read() readline() readlines()
*******************************************************************************************************************/

-- Python/R/Microsoft R

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# 파일 개체 = open(파일명, 파일 열기 모드)
#            r : read only
#            w : write only(if exists, overwrite file else create new file)
#            a : append (add write)
 
# ------------------------------
# -- open-close
# ------------------------------
fff = open('test_new.txt''w')
fff.close()
 
# -- write something on txt file.
fff = open('test_new.txt''w')
 
for i in range(0,5):
    ccc = '%d line...\n' %i
    fff.write(ccc)
 
fff.close()
 
# ------------------------------
# -- read first line from txt file.
# ------------------------------
fff = open('test_new.txt''r')
rrr = fff.readline()
print(rrr)
fff.close()
 
# -- read all line from txt file.
fff = open('test_new.txt''r')
 
while True:
    rrr = fff.readline()                 # no more line, return "None"
    if not rrr:
        break
    print(rrr)
 
# ------------------------------
# -- readlines를 통해 파일 내용을 리스트로 가져오기
# ------------------------------
fff = open('test_new.txt''r')
ddd = fff.readlines()
 
for d in ddd:
    print(d)
 
fff.close()
 
# ------------------------------
# -- .read()함수로 파일 읽기(파일 전체를 리턴)
# ------------------------------
fff = open('test_new.txt''r')
ddd = fff.read()
 
print('--------------------')
print(ddd)
 
fff.close()
 
# ------------------------------
# a모드를 이용해서 파일 편집
# ------------------------------
fff = open('test_new.txt''a')
 
for i in range(5,8):
    da = '%d번째 라인...\n' %i
    fff.write(da)
 
fff.close()
 
# ------------------------------
# with문으로 파일 객체 다루기
# with문 사용시 파일을 자동으로 닫아줌
# ------------------------------
fff=open('test_2.txt''w')
fff.write('파일 입출력 테스트')
fff.close()
 
with open('test_2.txt','w'as fff2:
    fff2.write('with문으로 파일 입출력 테스트-222222')
 
# ------------------------------
# import로 모듈 입력
# 난 안된다...
# ------------------------------
import sys
 
aaa = sys.argv[1:]
 
for i in aaa:
    print(i)
 
# cmd 창에서 > ttt.py aaa bbb ccc 확인
 

cs


반응형

+ Recent posts