문제: python에서 list의 append와 extend의 차이는?
해결:
append는 그냥 추가, extend는 까서 알맹이만 추가.
l = []
l.append([1, 1])
l.append([2, 2])
l은 [[1,1], [2,2]] # 그냥 추가함.
l.extend([1, 1])
l.extend([2, 2])
l은 [1, 1, 2, 2] # 까서 알맹이만 추가함.
2017년 11월 14일 화요일
2017년 9월 20일 수요일
python으로 list를 line-by-line으로 read와 write하자.
문제:
python으로 list를 line-by-line으로 read와 write하자.
해결:
def read_list_linebyline(fname): with open(fname) as fid: content = fid.readlines() content = [item.rstrip('\n') for item in content] return content
def write_list_linebyline(fname, thelist): fid = open(fname, 'w') for item in thelist: fid.write('%s\n' % (item)) fid.close()
2015년 12월 8일 화요일
python에서 폴더 내 파일 읽어오기 (리스트 형태), 폴더 생성하기
<출처: http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python>
// 특정 폴더의 파일(확장자가 ext인)을 읽어오고 싶은 경우 => 파일의 이름과 확장자만 리턴함.
import os def list_files(path, ext):// 특정 폴더 및 그 하위폴더의 파일(확장자가 ext인)까지 읽어오고 싶은 경우.=> 경로, 파일의 이름과 확장자 모두 리턴함.filelist = [] for name in os.listdir(path): if os.path.isfile(os.path.join(path, name)): if name.endswith(ext): filelist.append(name) return filelistimport os def list_files_subdir(destpath, ext): filelist = [] for path, subdirs, files in os.walk(destpath): for filename in files: f = os.path.join(path, filename) if os.path.isfile(f): if filename.endswith(ext): filelist.append(f) return filelistfilelist = list_files_subdir(strdirectory_fc, 'txt')// 특정 폴더 및 그 하위폴더의 파일(확장자가 ext인)까지 읽어오고 싶은 경우.=> 경로, 파일의 이름을 별도로 리턴함.import osdef list_files_subdir(destpath, ext): fullpathlist = [] folderlist = [] filelist = [] for path, subdirs, files in os.walk(destpath): for filename in files: f = os.path.join(path, filename) if os.path.isfile(f): if filename.endswith(ext): fullpathlist.append(f) folderlist.append(path) filelist.append(filename) return fullpathlist, folderlist, filelist// 특정 폴더 생성하기# 폴더가 존재하는지 확인 후, 없으면 생성함.strdirectory_fc = 'directory_name'
if not os.path.exists(strdirectory_fc):
os.makedirs(strdirectory_fc)
피드 구독하기:
글 (Atom)