Cómo abrir cada archivo en una carpeta?
Tengo un script python parse.py, que en el script abrir un archivo, decir file1, y luego hacer algo tal vez imprimir el número total de caracteres.
filename = 'file1'
f = open(filename, 'r')
content = f.read()
print filename, len(content)
En este momento, estoy usando stdout para dirigir el resultado a mi archivo de salida: output
python parse.py >> output
Sin embargo, no quiero hacer este archivo por archivo manualmente, ¿hay alguna manera de cuidar de cada archivo automáticamente? Como
ls | awk '{print}' | python parse.py >> output
Entonces el problema es ¿cómo podría leer el nombre del archivo de standardin? o hay ya algunas funciones incorporadas para hacer el ls y ese tipo de trabajo fácilmente?
Gracias!
6 answers
Puede listar todos los archivos en el directorio actual usando:
import os
for filename in os.listdir(os.getcwd()):
# do your stuff
O puede enumerar solo algunos archivos, dependiendo del patrón de archivo utilizando el módulo glob
:
import glob
for filename in glob.glob('*.txt'):
# do your stuff
No tiene que ser el directorio actual puede listarlos en cualquier ruta que desee:
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
O incluso puedes usar la tubería como especificaste usando fileinput
import fileinput
for line in fileinput.input():
# do your stuff
Y luego usarlo con tuberías:
ls -1 | python parse.py
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-15 23:13:22
Deberías intentar usar el sistema operativo.caminar
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-16 13:15:58
En realidad, puede usar el módulo del sistema operativo para hacer ambas cosas:
- lista todos los archivos en una carpeta
- ordenar archivos por tipo de archivo, nombre de archivo, etc.
Aquí hay un ejemplo simple:
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
Ahora no solo ha enumerado todos los archivos en una carpeta, sino que también los ha ordenado (opcionalmente) por nombre de inicio, tipo de archivo y otros. Ahora itera sobre cada lista y haz tus cosas.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-05 15:18:45
Solución fácil
Si desea abrir todos los archivos en la raíz de un directorio. He encontrado este problema muchas veces, así que creé un módulo fácil de usar para Python 3.5 y Python 2.7. Si tu versión de Python no está soportada solo pregúntame en GreyCadet IRC y agregaré el soporte.
Instalando el módulo
pip install filemapper
Uso
Considere una estructura de directorios como esta y que main.py es tu código.
-Program
-resources
nouns.txt
config.dat
help.txt
main.py
Contenido de main.py
import filemapper as fm
all_files = fm.load('resources') # fm.load('resources','w') will open in write mode
for f in all_files:
for i in fm.read(f):print i
Esto imprimirá las líneas de cada archivo en la carpeta recursos. También puede pasar cualquier modo.
Haciendo más
Si quieres hacer algo más que abrir archivos usando este módulo, visita la página de GitHub para más detalles.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-16 17:41:55
Estaba buscando esta respuesta:
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))
También puedes elegir'*.txt ' u otros extremos de su nombre de archivo
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-31 13:57:31
import pyautogui
import keyboard
import time
import os
import pyperclip
os.chdir("target 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('')
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-08 22:08:58