티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to open every file in a folder
폴더 내 모든 파일을 열 수 있는 방법
문제 내용
I have a python script parse.py, which in the script open a file, say file1, and then do something maybe print out the total number of characters.
파이썬 스크립트 parse.py가 있습니다. 이 스크립트에서는 파일을 열어서 (file1 같은) 어떤 작업을 수행하고 문자의 총 개수를 출력할 수도 있습니다.
filename = 'file1'
f = open(filename, 'r')
content = f.read()
print filename, len(content)
Right now, I am using stdout to direct the result to my output file - output
현재는 stdout을 사용하여 결과를 출력 파일(output)에 직접 보내고 있습니다.
python parse.py >> output
However, I don't want to do this file by file manually, is there a way to take care of every single file automatically? Like
그러나 파일을 수동으로 하나씩 처리하고 싶지 않습니다. 자동으로 각 파일을 처리하는 방법이 있을까요? 예를 들어
ls | awk '{print}' | python parse.py >> output
Then the problem is how could I read the file name from standardin? or there are already some built-in functions to do the ls and those kind of work easily?
이제 문제는 표준입력에서 파일 이름을 어떻게 읽을 수 있을까요? 아니면 이미 ls와 같은 작업을 수행하는 빌트인 함수가 있을까요?
Thanks!
감사합니다!
높은 점수를 받은 Solution
Os
You can list all files in the current directory using os.listdir
:
os.listdir를 사용하여 현재 디렉터리에 있는 모든 파일을 나열할 수 있습니다:
import os
for filename in os.listdir(os.getcwd()):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Glob
Or you can list only some files, depending on the file pattern using the glob
module:
glob 모듈을 사용하여 파일 패턴에 따라 일부 파일만 나열할 수도 있습니다:
import os, glob
for filename in glob.glob('*.txt'):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
It doesn't have to be the current directory you can list them in any path you want:
현재 디렉터리가 아니라 다른 경로에서도 나열할 수 있습니다:
import os, glob
path = '/some/path/to/file'
for filename in glob.glob(os.path.join(path, '*.txt')):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Pipe
Or you can even use the pipe as you specified using fileinput
fileinput을 사용하여 파이프로 연결하여 사용할 수도 있습니다.
import fileinput
for line in fileinput.input():
# do your stuff
And you can then use it with piping:
그리고 이를 파이핑과 함께 사용할 수 있습니다:
ls -1 | python parse.py
가장 최근 달린 Solution
import pyautogui
import keyboard
import time
import os
import pyperclip
os.chdir("target directory")
# get the current directory
cwd=os.getcwd()
files=[]
for i in os.walk(cwd):
for j in i[2]:
files.append(os.path.abspath(j))
os.startfile("C:\Program Files (x86)\Adobe\Acrobat 11.0\Acrobat\Acrobat.exe")
time.sleep(1)
for i in files:
print(i)
pyperclip.copy(i)
keyboard.press('ctrl')
keyboard.press_and_release('o')
keyboard.release('ctrl')
time.sleep(1)
keyboard.press('ctrl')
keyboard.press_and_release('v')
keyboard.release('ctrl')
time.sleep(1)
keyboard.press_and_release('enter')
keyboard.press('ctrl')
keyboard.press_and_release('p')
keyboard.release('ctrl')
keyboard.press_and_release('enter')
time.sleep(3)
keyboard.press('ctrl')
keyboard.press_and_release('w')
keyboard.release('ctrl')
pyperclip.copy('')
출처 : https://stackoverflow.com/questions/18262293/how-to-open-every-file-in-a-folder
'개발 > 파이썬' 카테고리의 다른 글
Pandas 데이터프레임에서 하나의 열을 기준으로 정렬하기 (0) | 2023.01.12 |
---|---|
Python에서 파일을 리스트로 읽는 방법 (0) | 2023.01.12 |
딕셔너리에서 key 이름을 변경하는 방법 (0) | 2023.01.11 |
판다스 데이터프레임이 비어 있는지 확인하는 방법 (0) | 2023.01.09 |
파이썬에서 리스트의 맨 앞에 정수 추가하기 (0) | 2023.01.08 |