폴더의 모든 파일을 여는 방법
저는 파이썬 스크립트 parse.py 을 가지고 있는데, 스크립트에서 파일을 열고 file1이라고 말한 다음, 무언가를 하면 총 문자 수를 출력할 수 있습니다.
filename = 'file1'
f = open(filename, 'r')
content = f.read()
print filename, len(content)
지금은 stdout을 사용하여 결과를 출력 파일 - 출력으로 보내고 있습니다.
python parse.py >> output
그런데 이 파일을 일일이 수동으로 하고 싶지 않은데, 모든 파일을 자동으로 처리할 수 있는 방법이 있나요?맘에 들다
ls | awk '{print}' | python parse.py >> output
그렇다면 문제는 어떻게 standardin에서 파일 이름을 읽을 수 있는가 하는 것입니다.아니면 이미 이런 종류의 일을 쉽게 할 수 있는 내장된 기능들이 있습니까?
감사합니다!
오스
다음을 사용하여 현재 디렉터리의 모든 파일을 나열할 수 있습니다.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모듈:
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
원하는 경로에 나열할 수 있는 현재 디렉터리일 필요는 없습니다.
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
파이프
또는 지정한 대로 파이프를 사용할 수도 있습니다.fileinput
import fileinput
for line in fileinput.input():
# do your stuff
그런 다음 파이프와 함께 사용할 수 있습니다.
ls -1 | python parse.py
사용해 보십시오.os.walk.
import os
yourpath = 'path'
for root, dirs, files in os.walk(yourpath, topdown=False):
for name in files:
print(os.path.join(root, name))
stuff
for name in dirs:
print(os.path.join(root, name))
stuff
저는 이 대답을 찾고 있었습니다.
import os,glob
folder_path = '/some/path/to/file'
for filename in glob.glob(os.path.join(folder_path, '*.htm')):
with open(filename, 'r') as f:
text = f.read()
print (filename)
print (len(text))
파일 이름의 '*.txt' 또는 다른 끝을 선택할 수 있습니다.
실제로 os 모듈을 사용하여 두 가지 작업을 모두 수행할 수 있습니다.
- 폴더의 모든 파일 나열
- 파일 형식, 파일 이름 등을 기준으로 파일을 정렬합니다.
다음은 간단한 예입니다.
import os #os module imported here
location = os.getcwd() # get present working directory location here
counter = 0 #keep a count of all files found
csvfiles = [] #list to store all csv files found at location
filebeginwithhello = [] # list to keep all files that begin with 'hello'
otherfiles = [] #list to keep any other file that do not match the criteria
for file in os.listdir(location):
try:
if file.endswith(".csv"):
print "csv file found:\t", file
csvfiles.append(str(file))
counter = counter+1
elif file.startswith("hello") and file.endswith(".csv"): #because some files may start with hello and also be a csv file
print "csv file found:\t", file
csvfiles.append(str(file))
counter = counter+1
elif file.startswith("hello"):
print "hello files found: \t", file
filebeginwithhello.append(file)
counter = counter+1
else:
otherfiles.append(file)
counter = counter+1
except Exception as e:
raise e
print "No files found here!"
print "Total files found:\t", counter
이제 폴더에 있는 모든 파일을 나열했을 뿐만 아니라 시작 이름, 파일 형식 등에 따라(선택적으로) 정렬됩니다.이제 각 목록을 반복하고 작업을 수행하십시오.
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('')
아래 코드는 실행 중인 스크립트가 포함된 디렉토리에서 사용 가능한 텍스트 파일을 읽습니다.그런 다음 모든 텍스트 파일을 열고 텍스트 줄의 단어를 목록에 저장합니다.단어를 저장한 후 각 단어를 한 줄씩 인쇄합니다.
import os, fnmatch
listOfFiles = os.listdir('.')
pattern = "*.txt"
store = []
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
_fileName = open(entry,"r")
if _fileName.mode == "r":
content = _fileName.read()
contentList = content.split(" ")
for i in contentList:
if i != '\n' and i != "\r\n":
store.append(i)
for i in store:
print(i)
디렉토리에서 파일을 열고 목록에 추가하려면 다음 작업을 수행합니다.
mylist=[]
for filename in os.listdir('path/here/'):
with open(os.path.join('path/here/', filename), 'r') as f:
mylist.append(f.read())
위의 옵션과 조금 다른 os.walk 및 os.path.dll을 사용하는 다른 접근법을 시도할 수 있습니다.
for root, dirs, files in os.walk(EnterYourPath):
for name in files:
with open(os.path.join(root,name))as f:
text = f.read()
텍스트 변수는 디렉터리의 폴더에 있는 모든 파일을 포함합니다.
언급URL : https://stackoverflow.com/questions/18262293/how-to-open-every-file-in-a-folder
'programing' 카테고리의 다른 글
| JavaScript:ASP.NET 코드백에서 Alert.Show(메시지) (0) | 2023.07.08 |
|---|---|
| 스프링 부트: 동적 상위 개체에서 JSON 응답 래핑 (0) | 2023.07.08 |
| PLSQL 하위 쿼리 및 반환 절을 사용하여 에 삽입 (0) | 2023.07.08 |
| Spring Boot에서 테스트 목적으로 DB 연결을 모의 실행하려면 어떻게 해야 합니까? (0) | 2023.07.08 |
| 문서 집합에 대한 각 값의 발생 횟수를 몽고 카운트 (0) | 2023.07.08 |