Ik heb een python-script parse.py, dat in het script een bestand opent, bijvoorbeeld file1, en dan iets doet dat misschien het totale aantal tekens afdrukt.
filename = 'file1'
f = open(filename, 'r')
content = f.read()
print filename, len(content)
Op dit moment gebruik ik stdout om het resultaat naar mijn uitvoerbestand te sturen – uitvoer
python parse.py >> output
Ik wil dit echter niet bestand voor bestand handmatig doen. Is er een manier om elk afzonderlijk bestand automatisch te regelen? Vind ik leuk
ls | awk '{print}' | python parse.py >> output
Het probleem is dan hoe ik de bestandsnaam van standardin kan lezen?
of zijn er al enkele ingebouwde functies om de ls en dat soort werk gemakkelijk te doen?
Bedankt!
Antwoord 1, autoriteit 100%
O’s
Je kunt alle bestanden in de huidige map weergeven met 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
Of u kunt slechts enkele bestanden weergeven, afhankelijk van het bestandspatroon met behulp van de module glob
:
import 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
Het hoeft niet de huidige map te zijn, je kunt ze in elk gewenst pad weergeven:
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
Pijp
Of u kunt zelfs de pijp gebruiken zoals u hebt opgegeven met fileinput
import fileinput
for line in fileinput.input():
# do your stuff
En u kunt het dan gebruiken met leidingen:
ls -1 | python parse.py
Antwoord 2, Autoriteit 10%
U moet proberen os.walk
te gebruiken.
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
Antwoord 3, Autoriteit 6%
Ik was op zoek naar dit antwoord:
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))
U kunt ook kiezen ‘* .txt’ of andere uiteinden van uw bestandsnaam
Antwoord 4, Autoriteit 3%
U kunt eigenlijk gewoon OS-module gebruiken om beide te doen:
- lijst alle bestanden in een map
- Sorteer bestanden per bestandstype, bestandsnaam enz.
Hier is een eenvoudig voorbeeld:
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
Nu heb je niet alleen alle bestanden in een map vermeld, maar heb je ze ook (optioneel) gesorteerd op startnaam, bestandstype en andere. Herhaal nu elke lijst en doe je ding.
Antwoord 5
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('')
Antwoord 6
De onderstaande code leest voor eventuele tekstbestanden die beschikbaar zijn in de map die het script bevat dat we actief zijn. Dan opent het elk tekstbestand en slaat de woorden van de tekstlijn op in een lijst. Na de woorden opslaan die we elke woordlijn per regel afdrukken
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)