file = open("C:\\python\\newFile.txt", "w"); file.close(); |
filePath = "C:\\python\\newFile.txt";
file = open(filePath, "w");
for i in range(1, 11): line = "%d Line. \n" %i; file.write(line);
file.close(); |
1 Line.
2 Line.
3 Line.
4 Line.
5 Line.
6 Line.
7 Line.
8 Line.
9 Line.
10 Line.
쓰기 모드로 열 때, 이미 존재하는 파일을 열면 파일 내용이 모두 사라진다.
filePath = "C:\\python\\newFile.txt";
file = open(filePath, "r"); line = file.readline(); file.close(); print(line); |
1 Line.
filePath = "C:\\python\\newFile.txt";
file = open(filePath, "r");
for line in file.readlines(): print(line);
file.close(); |
1 Line.
2 Line.
3 Line.
4 Line.
5 Line.
6 Line.
7 Line.
8 Line.
9 Line.
10 Line.
filePath = "C:\\python\\newFile.txt"; lastLength = sum(1 for line in open(filePath));
file = open(filePath, "a");
for i in range(lastLength + 1, 21): line = "%d Line. \n" % i; file.write(line);
file.close(); |
1 Line.
2 Line.
3 Line.
4 Line.
5 Line.
6 Line.
7 Line.
8 Line.
9 Line.
10 Line.
11 Line.
12 Line.
13 Line.
14 Line.
15 Line.
16 Line.
17 Line.
18 Line.
19 Line.
20 Line.
filePath = "C:\\python\\newFile.txt"; lastLength = sum(1 for line in open(filePath));
with open(filePath, "a") as file: for i in range(lastLength + 1, 21): line = "%d Line. \n" % i; file.write(line); |
file close를 대신 with 으로 처리 가능. C#의 using dispose개념인듯.
'Python' 카테고리의 다른 글
python class2 (0) | 2019.09.06 |
---|---|
python class (0) | 2019.09.04 |
python input, print (0) | 2019.09.02 |
python lambda (0) | 2019.09.02 |
python 함수3 (0) | 2019.09.02 |