I need to extract image header information from multiple JPG files to a text or log file, however when I run the code below I receive an error:
for root, dirs, filenames in os.walk(topdir):
for f in filenames:
print(topdir)
print(f)
log = open(topdir + f, 'r')
data = p.get_json(log)
formatted_data =(( json.dumps(data, sort_keys=True,indent=4, separators=(',', ':')) ))
print(data)
print ("There are " + str(len(header_dict)) + " items on the menu.")
I get the following error when I run:
C:/Users/richie/Desktop/work/imagej/test images and files/XX1
image_D2016-02-03T15-27-56-763207Z_4.jpg
Traceback (most recent call last):
File "C:\Users\richie\Desktop\work\header_dir.py", line 25, in <module>
log = open(topdir + f, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/richie/Desktop/work/imagej/test images and files/XX1image_D2016-02- 03T15-27-56-763207Z_4.jpg'
How do I open image files to allow the function in the for loop to run against it?
Your problem lies in this code;
topdir + f
First, you should use join on paths, not +. The latter doesn't insert the separator between the path and file.
Second, you should join a filename with root, not with topdir.
for root, dirs, files in os.walk(topdir):
paths = [os.path.join(root, f) for f in files]
for p in paths:
log = open(p)
# et cetera
Working code:
import pyexifinfo as x
import json
import os
from tkinter import *
from tkinter.filedialog import askopenfilename
def askdirectory():
dirname = filedialog.askdirectory()
return dirname
topdir = askdirectory()
for root, dirs, files in os.walk(topdir):
paths = [os.path.join(root, f) for f in files]
for p in paths:
data = x.get_csv(p)
print(p)
print(data)
formatted_data =((json.dumps(data, sort_keys=True,indent=4, separators=(',', ':')) ))
f = open('Xheader_info_XML.txt','a')
f.write(p)
f.write(formatted_data)
f.close()
Related
My code was working until yesterday, January 31, 2022. But today, Feb. 1, 2022, it sudden
Here's the error:
Traceback (most recent call last):
File "/Users/folder/code/3.cut_PDF.py", line 19, in
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
NotADirectoryError: [Errno 20] Not a directory: '/Users/.../Riskalyze/02.01.22/.DS_Store'
Here's my code:
import PyPDF2
from PyPDF2 import PdfFileWriter
from os import listdir
from os.path import isfile, join
import pandas as pd
from datetime import date
today_date = date.today().strftime("%m.%d.%y")
print(today_date)
mypath_folder = '/Users/.../Riskalyze/' + today_date + '/'
onlyfolder = [f for f in listdir(mypath_folder)]
print(onlyfolder)
pdfWriter = PdfFileWriter()
for folder in onlyfolder:
mypath = mypath_folder + folder
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
print(onlyfiles)
i = 0
if folder == "#Model":
model_name = []
print(type(model_name))
for file in onlyfiles:
file_name = file.rsplit(".")[0]
file_name = file_name.split("Portfolio")[0]
file_name = file_name + "Portfolio"
model_name.append(file_name)
print("model name:", model_name)
else:
pass
for file in onlyfiles:
print(file)
mypath_new = mypath + '/' + file
print(mypath_new)
pdfFileObj = open(mypath_new, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pageObj = pdfReader.getPage(0)
pdfWriter.addPage(pageObj)
i += 1
print("i:", i)
pdfOutputFile = open('/Users/.../Riskalyze/MergedFiles/MergedFiles_' + today_date + '.pdf', 'wb')
pdfWriter.write(pdfOutputFile)
pdfFileObj.close()
pdfOutputFile.close()
print(model_name)
(pathlib from the standard Python library is much more handy to use than os and os.path, I suggest you give it a try)
As for your problem,
onlyfolder = [f for f in listdir(mypath_folder)]
is wrong.
The doc for os.listdir :
Return a list containing the names of the entries in the directory given by path.
It lists the content of a directory, not just the directories in it. So you have a filename in your onlyfolder list, so that later when you do isfile(join(mypath, f)) it tries to access f (the file name) in the mypath directory, which happens to be a file (.DS_Store).
You could have found it yourself by using a debugger or simply printf-debugging.
I followed the instruction from internet to make a scripting for automating boring stuff in my computer.
I have some bugs when executing,
Could anyone show me what is the issue ? and suggestion for this case.
code :
# import python libraries
from os import listdir
from os.path import isfile, join
import os
import shutil
def file_organizer(mypath):
'''
A function to sort the files in a download folder
into their respective categories
'''
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
file_type_variation_list = []
filetype_folder_dict = {}
for file in files:
filenamebrake = file.split('.')
filetype = filenamebrake[len(filenamebrake) - 1]
if filetype not in file_type_variation_list:
file_type_variation_list.append(filetype)
new_folder_name = mypath + '/' + filetype + '_folder'
filetype_folder_dict[str(filetype)] = str(new_folder_name)
if os.path.isdir(new_folder_name) == True: # folder exists
continue
else:
os.mkdir(new_folder_name)
for file in files:
src_path = mypath + '/' + file
filenamebrake = file.split('.')
filetype = filenamebrake[len(filenamebrake) - 1]
if filetype in filetype_folder_dict.keys():
dest_path = filetype_folder_dict[str(filetype)]
shutil.move(src_path, dest_path)
print("File Organization Completed " + str(mypath))
mypath = 'C:/Users/snguyend/Downloads'
mypath = str(input("Enter Path "))
file_organizer(mypath)
Error message when executing the cmd
C:\Users\snguyend\Desktop\Python Anaconda>python organizebot.py
Enter Path
Traceback (most recent call last):
File "organizebot.py", line 40, in <module>
file_organizer(mypath)
File "organizebot.py", line 14, in file_organizer
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
FileNotFoundError: [WinError 3] The system cannot find the path specified: ''
C:\Users\snguyend\Desktop\Python Anaconda>
Link to code
I have a python script that reads a file and copies its content to another file while deleting unwanted lines before sending.
The problem is that I want to allow the user to choose the source file and the destination path.
How can this be solved ?
outputSortedFiles.py
#!/usr/bin/python
'''FUNCTION THAT READ SELECTE DFILE AND WRITE ITS
CONTENT TO SECOND FILE WITH DELETING
TH EUNWANTED WORDS'''
import Tkinter
from os import listdir
from os.path import isfile
from os.path import join
import tkFileDialog
import os
def readWrite():
unwanted = ['thumbnails', 'tyroi', 'cache', 'Total files', 'zeryit', 'Ringtones', 'iconRecv',
'tubemate', 'ueventd', 'fstab', 'default', 'lpm']
mypath = r"C:\Users\hHJE\Desktop/filesys"
Tkinter.Tk().withdraw()
in_path = tkFileDialog.askopenfile(initialdir = mypath, filetypes=[('text files', ' TXT ')])
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for file in files:
if file.split('.')[1] == 'txt':
outputFileName = 'Sorted-' + file
with open(mypath + outputFileName, 'w') as w:
with open(mypath + '/' + file) as f:
for l in f:
if not True in [item in l for item in unwanted]:
w.write(l)
print ("
*********************************\
THE OUTPUT FILE IS READY\
*********************************\
")
in_path.close()
if __name__== "__main__":
readWrite()
You can use TkFileDialog just as you did to ask inputFiles :
outputpath = tkFileDialog.asksaveasfile()
See examples in those tutorials : http://www.tkdocs.com/tutorial/windows.html
If you simply want the user to choose the directory:
from tkinter import filedialog
outputpath = filedialog.askdirectory()
I'm trying to write a Python script that loops through all text files in a directory and deletes any file that has lines that start with 1.
I tried to do it with python, but I don't know how.
My code:
import os
import re
import string
filedir = "C:\Users\Mr The Vinh\Downloads\ver 3.0.2.4\ver 3.0.2.4\baiviet_da_thay_link\test"
t = 0
for root, dirs, filenames in os.walk(filedir):
for f in filenames:
path = os.path.join(root, f)
text = open(path, 'r')
delkey = re.search(r'^1',text.read())
if delkey:
t = t + 1
os.remove(path)
print 'We deleted file:', t
when i run i saw
Process finished with exit code 0 with no erro code
I believe you should iterate over lines with for line in text.readlines(): to check starting of line.
import os
import re
import string
filedir = "C:\Users\Mr The Vinh\Downloads\ver 3.0.2.4\ver 3.0.2.4\baiviet_da_thay_link\test"
t = 0
for root, dirs, filenames in os.walk(filedir):
for f in filenames:
path = os.path.join(root, f)
text = open(path, 'r')
for line in text.readlines():
delkey = re.search(r'^1',line)
if delkey:
t = t + 1
os.remove(path)
break
print 'We deleted file:', t
This question is how to get list of files from a directory into text file using python.
Result in the text file should exactly be like this:
E:\AA\a.jpg
E:\AA\b.jpg
...
How to correct the code below:
WD = "E:\\AA"
import glob
files = glob.glob ('*.jpg')
with open ('infiles.txt', 'w') as in_files:
in_files.write(files +'\n')
glob.glob() returns a list. You have to iterate through it.
WD = "E:\\AA"
import glob
files = glob.glob ('*.jpg')
with open ('infiles.txt', 'w') as in_files:
for eachfile in files: in_files.write(eachfile+'\n')
Input directory path : WD = "E://AA"
You can assign specific file extention that you needed eg: path = WD+'/*.jpg',
if you need all file list then give '' eg: path = WD+'/'
import glob
w_dir = WD + "/*.jpg"
with open("infiles.txt","wb")as fp:
for path in [filepath for filepath in glob.glob(w_dir)]:
fp.write(path+"\n")
Without path, glob.glob returns list of filename (No directory part). To get full path you need to call os.path.abspath(filename) / os.path.realpath(filename) / os.path.join(WD, filename)
>>> glob.glob('*.png')
['gnome-html.png', 'gnome-windows.png', 'gnome-set-time.png', ...]
>>> os.path.abspath('gnome-html.png')
'/usr/share/pixmaps/gnome-html.png'
With path, glob.glob return list of filename with directory part.
>>> glob.glob('/usr/share/pixmaps/*.png')
['/usr/share/pixmaps/gnome-html.png', '/usr/share/pixmaps/gnome-windows.png', '/usr/share/pixmaps/gnome-set-time.png', ...]
import glob
import os
WD = r'E:\AA'
files = glob.glob(os.path.join(WD, '*.jpg'))
with open('infiles.txt', 'w') as in_files:
in_files.writelines(fn + '\n' for fn in files)
or
import glob
import os
WD = r'E:\AA'
os.chdir(WD)
files = glob.glob('*.jpg')
with open('infiles.txt', 'w') as in_files:
in_files.writelines(os.path.join(WD, fn) + '\n' for fn in files)
Here is a two line simple solution:
import os
filee = open('all_names.txt','w')
given_dir = 'the_dierctory'
[filee.write(os.path.join(os.path.dirname(os.path.abspath(__file__)),given_dir,i)+'\n') for i in os.listdir(given_dir)]
where given_dir is the directory name. The output is a text file (all_names.txt) where each line in the file is the full path to all files and directories in the given_dir.