Programming

폴더의 모든 파일을 여는 방법은 무엇입니까?

procodes 2020. 7. 13. 21:48
반응형

폴더의 모든 파일을 여는 방법은 무엇입니까?


나는 파이썬 스크립트 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에서 파일 이름을 어떻게 읽을 수 있습니까? 또는 ls와 그러한 종류의 작업을 쉽게 수행하는 내장 함수가 이미 있습니까?

감사!


다음을 사용하여 현재 디렉토리의 모든 파일을 나열 할 수 있습니다.

import os
for filename in os.listdir(os.getcwd()):
   # do your stuff

또는 glob모듈을 사용하여 파일 패턴에 따라 일부 파일 만 나열 할 수 있습니다 .

import glob
for filename in glob.glob('*.txt'):
   # do your stuff

원하는 경로에 나열 할 수있는 현재 디렉토리 일 필요는 없습니다.

path = '/some/path/to/file'

for filename in os.listdir(path):
    # do your stuff

for filename in glob.glob(os.path.join(path, '*.txt')):
    # do your stuff

또는 파이프를 사용하여 지정한대로 사용할 수도 있습니다 fileinput

import fileinput
for line in fileinput.input():
    # do your stuff

그런 다음 배관과 함께 사용하십시오.

ls -1 | python parse.py

os.walk를 사용해보십시오

yourpath = 'path'

import os
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

실제로 os 모듈사용 하여 두 가지를 모두 수행 할 수 있습니다.

  1. 폴더의 모든 파일을 나열합니다
  2. 파일 형식, 파일 이름 등으로 파일 정렬

다음은 간단한 예입니다.

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 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'또는 파일 이름의 다른 끝을 선택할 수도 있습니다


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('')

참고 URL : https://stackoverflow.com/questions/18262293/how-to-open-every-file-in-a-folder

반응형