티스토리 뷰

INTRO

Text, .txt file 다루기

 - iterm.app or terminal.app : file handling

 - python file handling

File Handling : Create, Open/Close, Append, Read, Write

 

용어

Text File(텍스트 파일, .txt)

사람이 인지할 수 있는 문자열 집합으로부터 문자열로만 이루어진다.

잘 알려진 문자열 집합으로는 ASCII 문자열 집합과 유니코드 문자열 집합이 있다.

출처 : ko.wikipedia.org/wiki/텍스트_파일

 

ASCII

미국정보교환표준부호(American Standard Code for Information Interchange)

줄여서 ASCII( /ˈæski/, 아스키)는 영문 알파벳을 사용하는 대표적인 문자 인코딩

컴퓨터와 통신 장비를 비롯한 문자를 사용하는 많은 장치에서 사용되며, 대부분의 문자 인코딩이 아스키에 기초를 두고 있다.

출처 : ko.wikipedia.org/wiki/ASCII

 

유니코드(Unicode)

유니코드(Unicode)는 전 세계의 모든 문자를 컴퓨터에서 일관되게 표현하고 다룰 수 있도록 설계된 산업 표준이며, 유니코드 협회(Unicode Consortium)가 제정한다.

또한 유니코드의 목적은 현존하는 문자 인코딩 방법들을 모두 유니코드로 교체하려는 것이다. 기존의 인코딩들은 그 규모나 범위 면에서 한정되어 있고, 다국어 환경에서는 서로 호환되지 않는 문제점이 있었다.

유니코드가 다양한 문자 집합들을 통합하는 데 성공하면서 유니코드는 컴퓨터 소프트웨어의 국제화와 지역화에 널리 사용되게 되었으며, 비교적 최근의 기술인 XML, 자바, 그리고 최신 운영 체제 등에서도 지원하고 있다.

출처 : ko.wikipedia.org/wiki/유니코드

 

UTF-8 : python3에서 주석으로 한글 인코딩 --> # -*- coding: utf-8 -*-

UTF-8은 유니코드를 위한 가변 길이 문자 인코딩 방식 중 하나로, 켄 톰프슨과 롭 파이크가 만들었다. UTF-8은 Universal Coded Character Set + Transformation Format – 8-bit 의 약자이다. 본래는 FSS-UTF(File System Safe UCS/Unicode Transformation Format)라는 이름으로 제안되었다.

UTF-8 인코딩은 유니코드 한 문자를 나타내기 위해 1바이트에서 4바이트까지를 사용한다. 

출처 : ko.wikipedia.org/wiki/UTF-8

 

 

1. terminal command line : file handling

iterm2 + oh my zsh 환경에 따라 다르지만 "~"은 macOS home dir 

clear : terminal 화면 청소

pwd : Print Working Directory, 현재 dir 경로

cd : Change Directory, 사용법 --> 절대경로 이동 cd ./dir_name/dir_name, 상위폴도 이동 cd ..

ls : list, 권한/소유권/파일크기/생성일/dir_name or file_name

mkdir : Make Directory, dir 생성, 사용법 --> mk dir_name

rmdir : Remove Directory, dir 제거, rmdir dir_name

touch : create file/modify date..., 사용법 --> touch file_name

rm : Remove, file 제거, rm file_name

cat : Concatenate, file 읽기, 사용법 --> cat file_name

cp : Copy, 복사하기, 사용법 --> cp file_name path

mv : Move, 이동하기, 사용법 --> mv file_name path

nano : text editor, vi editor 사용이 편리, 사용법 --> nano file_name --> 편집 --> ctrl+o & enter 저장 --> ctrl+x 나오기

 

ex1> clear, pwd, cd, ls -al, ls -a, ls -l, ls

➜  ~ clear
➜  ~ 

➜  ~ pwd
/Users/[YourID]

➜  ~ cd ./pyTest
➜  pyTest ls -al
total 136
drwxr-xr-x  17 [YourID]  staff   544  3  3 15:20 .
drwxrwxrwx@ 25 [YourID]  staff   800  3  3 15:20 ..
-rw-r--r--@  1 [YourID]  staff  6148  3  3 15:17 .DS_Store
-rw-r--r--   1 [YourID]  staff   638  3  3 11:22 example_import.py
drwxr-xr-x   4 [YourID]  staff   128  3  2 14:04 myClass
drwxr-xr-x   4 [YourID]  staff   128  3  2 16:15 myfun
-rw-r--r--@  1 [YourID]  staff   285  2 22 17:10 test0.py
-rwxrw-rw-   1 [YourID]  staff   310  2 22 17:54 test1.py
-rw-r--r--   1 [YourID]  staff   619  3  2 17:20 test10.py
-rw-r--r--   1 [YourID]  staff  1787  2 24 13:50 test2.py
-rw-r--r--   1 [YourID]  staff  3229  2 25 11:11 test3.py
-rw-r--r--   1 [YourID]  staff  4254  2 25 12:30 test4.py
-rw-r--r--   1 [YourID]  staff  3820  2 25 15:25 test5.py
-rw-r--r--   1 [YourID]  staff  3737  2 25 16:31 test6.py
-rw-r--r--   1 [YourID]  staff  4585  2 26 14:48 test7.py
-rw-r--r--   1 [YourID]  staff  4729  2 27 14:55 test8.py
-rw-r--r--   1 [YourID]  staff   823  3  2 08:46 test9.py


➜  pyTest ls -a
.                 myfun             test3.py          test8.py
..                test0.py          test4.py          test9.py
.DS_Store         test1.py          test5.py
example_import.py test10.py         test6.py
myClass           test2.py          test7.py


➜  pyTest ls -l
total 120
-rw-r--r--  1 [YourID]  staff   638  3  3 11:22 example_import.py
drwxr-xr-x  4 [YourID]  staff   128  3  2 14:04 myClass
drwxr-xr-x  4 [YourID]  staff   128  3  2 16:15 myfun
-rw-r--r--@ 1 [YourID]  staff   285  2 22 17:10 test0.py
-rwxrw-rw-  1 [YourID]  staff   310  2 22 17:54 test1.py
-rw-r--r--  1 [YourID]  staff   619  3  2 17:20 test10.py
-rw-r--r--  1 [YourID]  staff  1787  2 24 13:50 test2.py
-rw-r--r--  1 [YourID]  staff  3229  2 25 11:11 test3.py
-rw-r--r--  1 [YourID]  staff  4254  2 25 12:30 test4.py
-rw-r--r--  1 [YourID]  staff  3820  2 25 15:25 test5.py
-rw-r--r--  1 [YourID]  staff  3737  2 25 16:31 test6.py
-rw-r--r--  1 [YourID]  staff  4585  2 26 14:48 test7.py
-rw-r--r--  1 [YourID]  staff  4729  2 27 14:55 test8.py
-rw-r--r--  1 [YourID]  staff   823  3  2 08:46 test9.py

➜  pyTest ls
example_import.py test1.py          test4.py          test8.py
myClass           test10.py         test5.py          test9.py
myfun             test2.py          test6.py
test0.py          test3.py          test7.py

ex2> lecture_basic_1to5 directory 생성 후 test0.py~test10.py와 example_import.py 이동

        macOS에서 네트워크 상 파일 이동시 .DS_Store 파일이 생성된다고 한다. 제거해보자. 추가내용 참고 : (macOS) .DS_Store 삭제

➜  pyTest mkdir lecture_basic_1to5


➜  pyTest mv *.py ./lecture_basic_1to5


➜  pyTest ls ./lecture_basic_1to5	# 이동된 dir 확인
example_import.py test10.py         test4.py          test7.py
test0.py          test2.py          test5.py          test8.py
test1.py          test3.py          test6.py          test9.py


➜  pyTest ls	# 현재 dir 확인
lecture_basic_1to5 myClass            myfun


➜  pyTest ls -a
.                  .DS_Store          myClass
..                 lecture_basic_1to5 myfun


➜  pyTest rm .DS_Store	# .DS_Store 제거


➜  pyTest ls -a		# 제거 후 확인
.                  lecture_basic_1to5 myfun
..                 myClass

 

ex2> py_intro.txt 파일 생성 후 nono editor에 내용(본문참고 : INTRO., 아래 파일 첨부)을 복사 후 붙여 넣고 cat 명령어로 읽기

➜  pyTest touch py_intro.txt


➜  pyTest ls
lecture_basic_1to5 myClass            myfun              py_intro.txt


➜  pyTest nano py_intro.txt		# 아래 캡쳐 화면 참고


➜  pyTest cat py_intro.txt
python(파이썬)

1991년 프로그래머인 귀도 반 로섬이 발표한 고급 프로그래밍 언어로, 플랫폼에 독립적이며 인터프리터식, 객체지향적, 동적 타이핑(dynamically typed) 대화형 언어

...(중략)

파이썬으로 할 수 없는 일

시스템과 밀접한 프로그래밍 영역
모바일 프로그래밍

출처 : 위키독, wikidocs.net/7


➜  pyTest

py_intro.txt
0.00MB

 

GNU nano Editor

 

2. python : file handling

python에서 경로는 cwd(current work directory) 기준 상대경로(./)를 이용한다.

cwd에서 base_path, sub_dirs, files를 얻고 새로운 디렉토리와 파일을 생성해보자.

file은 open/close를 이용하지만 with를 이용하면 close없이 간결하게 사용할 수 있다.

.txt file을 생성하고, 위의 "py_intro.txt" 파일을 열어 내용을 읽고 생성된 파일에 쓰는 방법을 알아본다.

 

python code : pyTest/test11.py

# -*- coding: utf-8 -*-
import os


#### directory : path, make dir, make txt
print("현재 경로만 얻기 : os.getcwd\n{}\n".format(os.getcwd()))
print("현재 경로 files와 sub_dirs 얻기 : os.listdir\n{}\n".format(os.listdir(os.getcwd())))

print("현재 경로, 하위 디렉토리명, 파일명 : os.walk")
base_path, sub_dirs, fnames = next(os.walk(os.getcwd()))
print("1.base_path\n{}\n2.sub_dirs\n{}\n3.files\n{}\n".format(base_path, sub_dirs, fnames))

new_sub_dir = 'lecture_basic_6to10'
new_file = 'py_intro_cp.txt'
print("Make Path : sub_dir in cwd(current working directory)")

sub_dpath = os.path.join(base_path,new_sub_dir)
new_fpath = os.path.join(base_path,new_file)
print("Path of new_sub_dir : {}".format(sub_dpath))
print("Path of new_file    : {}".format(new_fpath))

print("Before confirm making sub_dir/file : {}".format(os.listdir(os.getcwd())))
if not os.path.isdir(sub_dpath):
	os.makedirs(sub_dpath)
if not os.path.isfile(new_fpath):
	f = open(new_file,'w')
	f.close()
print("After confirm making sub_dir/file : {}".format(os.listdir(os.getcwd())))


#### directory : txt open/close using with, txt read/write
with open("py_intro.txt",'r') as f1:
	text_read = f1.read()
	with open(new_file,'a') as f2:
		f2.write(text_read)

## 생성된 py_intro_cp.txt 파일을 열어 내용을 확인

 

---- SublimeText python Run test11.py ----

현재 경로만 얻기 : os.getcwd
~/pyTest

현재 경로 files와 sub_dirs 얻기 : os.listdir
['py_intro.txt', 'lecture_basic_1to5', 'myClass', 'myfun', 'test11.py']

현재 경로, 하위 디렉토리명, 파일명 : os.walk
1.base_path
~/py_design_tool/pyTest
2.sub_dirs
['lecture_basic_1to5', 'myClass', 'myfun']
3.files
['py_intro.txt', 'test12.py', 'test11.py']

Make Path : sub_dir in cwd(current working directory)
Path of new_sub_dir : ~/pyTest/lecture_basic_6to10
Path of new_file    : ~/pyTest/py_intro_cp.txt
Before confirm making sub_dir/file : ['py_intro.txt', 'lecture_basic_1to5', 'myClass', 'myfun', 'test11.py', 'py_intro_cp.txt', 'lecture_basic_6to10']
After confirm making sub_dir/file : ['py_intro.txt', 'lecture_basic_1to5', 'myClass', 'myfun', 'test11.py', 'py_intro_cp.txt', 'lecture_basic_6to10']

***Repl Closed***

 

 

python code : pyTest/ref11.py

아스키코드와 진법 변환/역변환

dir(), locals(), vars()는 python 구동에 사용되는 object 내용 및 경로 확인에 활용

# -*- coding: utf-8 -*-
import os

#### ASCII, 진법
print("문자   --> ASCII : chr(65)  = {}".format(chr(65)))
print("ASCII --> 문자   : ord('A') = {}\n".format(ord('A')))

print("10진수 -->  2진수 : bin(3)        = {}".format(bin(3)))
print("10진수 -->  2진수 : bin(-3)       = {}".format(bin(-3)))
print(" 2진수 --> 10진수 : int('0b11',2) = {}".format(int('0b11',2)))

#### dir, locals 활용
print('\n\n')
print("dir() : {}\n".format(dir()))
print("dir(os) : {}\n".format(dir(os)))
## locals() 딕셔너리는 읽기에만 유용
print("locals() : {}\n".format(locals()))
print("locals()['os'] : {}\n".format(locals()['os']))
## vars()는 인자가 없으면 locals() 처럼 동작 : 아래 주석 풀어서 확인
# print("vars() {}\n".format(vars()))
# print("vars(os) {}\n".format(vars(os)))

 

---- SublimeText python Run ref11.py : dir(os)는 os module이 사용할 수 있는 mothod를 보여준다. 너무 길어서 중략----

문자   --> ASCII : chr(65)  = A
ASCII --> 문자   : ord('A') = 65

10진수 -->  2진수 : bin(3)        = 0b11
10진수 -->  2진수 : bin(-3)       = -0b11
 2진수 --> 10진수 : int('0b11',2) = 3



dir() : ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'os']

dir(os) : ['CLD_CONTINUED',  ... 
'__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', ... 
'close', 'closerange', ... 
'getcwd', 'getcwdb', 'getegid', 'getenv', 'getenvb', 'geteuid', 'getgid', ... 
'makedirs', 'minor', 'mkdir', 'mkfifo', 'mknod', 'name', 'nice', 'open', ... 
'read', 'readlink', 'readv', 'register_at_fork', 'remove',  ... 
'sys', 'sysconf', 'terminal_size', 'times', ... ]

locals() : {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x108ee5ca0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/jiwonlee/py_design_tool/pyTest/ref11.py', '__cached__': None, 'os': <module 'os' from '/usr/local/Cellar/python@3.9/3.9.1_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py'>}

locals()['os'] : <module 'os' from '/usr/local/Cellar/python@3.9/3.9.1_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py'>


***Repl Closed***
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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
글 보관함