Error 32, Python, file being used by another process - python

I have a simple program, which looks for all compressed folders in a directory, targets one compressed file, gets an excel file located inside the compressed file and moves it to another location (it does this for every excel file, for how many ever compressed folders):
path = 'C:\Users\me\Documents\Extract'
new_path = 'C:\Users\me\Documents\Test'
i = 0
for folder in os.listdir(path):
path_to_folder = os.path.join(path, folder)
zfile = zipfile.ZipFile(os.path.join(path, folder))
for name in zfile.namelist():
if name.endswith('.xls'):
new_name = str(i)+'_'+name
new_path = os.path.join(new_path, new_name)
zfile.close()
#os.rename(path_to_folde, new_path) -- ERROR HERE
shutil.move(path_to_folde, new_path) -- AND ERROR HERE
i += 1
I have tried 2 ways to move the excel file os.rename and shutil.move. I keep on getting an error:
WindowsError: [Error 32] The process cannot access the file beacause it is being used by another process.
I don't understand why this error persists, since I have closed every folder.

path = 'C:\Users\me\Documents\Extract'
destination_path = 'C:\Users\me\Documents\Test'
i = 0
for folder in os.listdir(path):
path_to_zip_file = os.path.join(path, folder)
zfile = zipfile.ZipFile(path_to_zip_file)
for name in zfile.namelist():
if name.endswith('.xls'):
new_name = str(i)+'_'+name
new_path = os.path.join(destination_path, new_name)
# This is obviously going to fail because we just opened it
shutil.move(path_to_zip_file, new_path)
i += 1
zfile.close()
Changed some of the variable names in your code snippet. Do you see your problem now? You're trying to move the zip file that your process has open. You'll need to copy the .xls file to your destination using the zipfile module.

If you are on a windows computer go to the task manager and hit the processes tab. Scroll down to anything that says python and end the process. You may have had python running with something else. Then try running your python program again and it should work.

downloaded files must be marked as 'unblock' in the properties window of the file
before they can be worked with code.

Related

For loop with files with Python

I have this code:
import os
directory = "JeuDeDonnees"
for filename in os.listdir(directory):
print("File is: "+filename)
This code run and prints files name in a VSCode/Python environment.
However, when I run it in Sikuli-IDE I got this error:
[error] SyntaxError ( "no viable alternative at input 'for'", )
How can I make this for loop run or is there an alternative that can work?
Answer found ;
Basically, in my Sikuli-IDE environnement, there's layers of Python, Java, Jython... interlocking each other so the Path finding was tedious.
src_file_path = inspect.getfile(lambda: None) #The files we're in
folder = os.path.dirname(src_file_path) # The folder we're in
directory = folder + "\JeuDeDonnees" # Where we wanna go
for filename in os.listdir(directory) # Get the files
print(filename)
We're telling the Path where we are with the current file, get the folder we're in, then moving to "\JeuDeDonnees" and the files.

Unable to save file in folder using python open()

My English is very poor, and the use of the Google translation, I am sorry for that. :)
Unable to save filename, error indicating no directory exists, but directory exists.
1.You can manually create the file in the resource manager --> the file name is legal.
2.You can manually create a directory in the resource manager --> the directory name is legal
3.You can save other file names such as aaa.png to this directory, that is, this directory can be written to other files --> The path path is legal, there is no permission problem, and there is no problem with the writing method.
4.The file can be written to the upper-level directory download_pictures --> It's not a file name problem.
thank you!!!
import os
path = 'download_pictures\\landscape[or]no people[or]nature[OrderBydata]\\'
download_name = '[6]772803-2500x1459-genshin+impact-lumine+(genshin+impact)-arama+(genshin+impact)-aranara+(genshin+impact)-arabalika+(genshin+impact)-arakavi+(genshin+impact).png'
filename = path + download_name
print('filename = ', filename)
# Create the folder make sure the path exists
if not os.path.exists(path):
os.makedirs(path)
try:
with open(filename, 'w') as f:
f.write('test')
except Exception as e:
print('\n【error!】First save file, failed, caught exception:', e)
print(filename)
filename = path + 'aaa.png'
with open(filename, 'w') as f:
print('\nThe second save file, changed the file name aaa.png, the path remains unchanged')
f.write('test')
print(filename)
path = 'download_pictures\\'
filename = path + download_name
with open(filename, 'w') as f:
print('\nThe third save file, the file name is unchanged, but the directory has changed')
f.write('test')
console
filename = download_pictures\landscape[or]no people[or]nature[OrderBydata]\[6]772803-2500x1459-genshin+impact-lumine+(genshin+impact)-arama+(genshin+impact)-aranara+(genshin+impact)-arabalika+(genshin+impact)-arakavi+(genshin+impact).png
【error!】First save file, failed, caught exception: [Errno 2] No such file or directory: 'download_pictures\\landscape[or]no people[or]nature[OrderBydata]\\[6]772803-2500x1459-genshin+impact-lumine+(genshin+impact)-arama+(genshin+impact)-aranara+(genshin+impact)-arabalika+(genshin+impact)-arakavi+(genshin+impact).png'
download_pictures\landscape[or]no people[or]nature[OrderBydata]\[6]772803-2500x1459-genshin+impact-lumine+(genshin+impact)-arama+(genshin+impact)-aranara+(genshin+impact)-arabalika+(genshin+impact)-arakavi+(genshin+impact).png
The second save file, changed the file name aaa.png, the path remains unchanged
download_pictures\landscape[or]no people[or]nature[OrderBydata]\aaa.png
The third save file, the file name is unchanged, but the directory has changed
Process finished with exit code 0
I couldn't replicate your error (I'm using linux and I think you have a Windows system), but anyway, you should not try to join paths manually. Instead try to use os.path.join to join multiple paths to one valid path. This will also ensure that based on your operating system the correct path separators are used (forward slash on unix and backslash on Windows).
I have adapted the code until the first saving attempt accordingly and it writes a file correctly. Also, the code gets cleaner this way and it's easier to see the separate folder names.
import os
if __name__ == '__main__':
path = os.path.join('download_pictures', 'landscape[or]no people[or]nature[OrderBydata]')
download_name = '[6]772803-2500x1459-genshin+impact-lumine+(genshin+impact)-arama+(genshin+impact)-aranara+(genshin+impact)-arabalika+(genshin+impact)-arakavi+(genshin+impact).png'
filename = os.path.join(path, download_name)
print('filename = ', filename)
# Create the folder make sure the path exists
if not os.path.exists(path):
os.makedirs(path)
try:
with open(filename, 'w') as f:
f.write('test')
except Exception as e:
print('\n【error!】First save file, failed, caught exception:', e)
print(filename)
I hope this helps. I think the issue with your approach is related to the path separators \\ under Windows.

How to create file .txt in a specific path of a directory

i want to create a text file in a specified directory. as shown below in the code, i am trying to create di.txt in pathToOutputDir but when i run the code, i find that di.txt is created as a yellow directory not a
as a text file that can be opened with notepad.
please let me know how to fix this code to create a .txt file.
Code :
def createOutPutDirectoryFor(self,directory):
pathToOutputDir = os.path.join(os.getcwd(), directory)
pathToOutputDir = os.path.join(pathToOutputDir, "di.txt")
It's difficult to tell what you are doing wrong, as you didn't include the part in your code that creates the file/directory. However, you're most likely using os.mkdir instead of creating a file.
You can do the following to create the file:
def createOutPutDirectoryFor(self,directory):
pathToOutputDir = os.path.join(os.getcwd(), directory)
pathToOutputDir = os.path.join(pathToOutputDir, "di.txt")
open(pathToOutputDir, 'a').close()
In your code, you create the path but don't actually create the file-
You can use the following to create the file:
open(pathToOutputDir, "x").close()
If you have fullpath of that directory then
def createOutPutDirectoryFor(self,directory):
pathToOutputDir = os.path.join(os.getcwd(), directory)
pathToOutputDir = os.path.join(pathToOutputDir, "di.txt")
try:
open(pathToOutputDir, 'a').close()
except FileNotFoundError:
open(pathToOutputDir, 'w').close()

Python - IOError when running through folder tree

I am trying to read in a series of DICOM files in a folder tree and I am using the below code to run through the tree, reading in each file as I go. The problem is I am getting IOErrors for files that definitely exist, I have checked file permissions and other SO threads such as Python: IOError: [Errno 2] No such file or directory but I haven't managed to get it working without these IOErrors yet. Does anyone have any ideas?
for root, dirs, files in os.walk(path):
for fname in files:
name = os.path.basename(os.path.abspath(fname))
if name.startswith('.') == True:
pass
else:
try:
plan=dicom.read_file(fname)
ds=dicom.read_file(fname, stop_before_pixels = True)
kVp = TagChecker([0x18,0x60]) #KVP
Target = TagChecker([0x18,0x1191]) #ANODE
Filter = TagChecker([0x18,0x7050]) #
write_results.writerow([Survey_Number, Patient_ID, View_Protocol, int(kVp), Target, Filter, Thickness, mAs_Exposure, LPad_Yes_No, autoorman, AECMode, AECDset, Patient_Age, Comment, Compression_Force])
#print(fname)
except IOError:
print "IOError: ", "//" + os.path.join(root, fname) + "//"
except InvalidDicomError:
# This exception line prints an error message to the command line, checks to see if an error log
# has been generated for this session, writes a new one if not and then writes the error to the log file
print "Invalid Dicom File: ", fname
Usually a method that takes a filename, like dicom.read_file(fname), will take an absolute filename (or assume that the filename is relative to the dir that your main python program is running in, the cwd()). Can I suggest that you put this line in front of the first read_file() call:
print "reading: %s" % os.path.abspath(fname)
Then you'll see the filename that you're actually trying to read. I'm guessing it's not the file (or droids) you think you're looking for.
In order to fix your problem.. join the dir and the fname before you read.. e.g.
full_fname = os.path.join(dir, fname)
dicom.read_file(full_fname)
In other words, I think you're reading files with relative paths and you want to be using absolute paths.

os.rename() file to part of folder name

I have multiple folders that look like folder.0 and folder.1.
Inside each folder there is one file ('junk') that I want to copy and rename to the .0 or .1 part of the folder name in which it currently resides.
Here is what I'm trying to do:
inDirec = '/foobar'
outDirec = '/complete/foobar'
for root, dirs,files in os.walk(inDirec):
for file in files:
if file =='junk'
d = os.path.split(root)[1]
filename, iterator = os.path.splitext(d) # folder no. captured
os.rename(file, iterator+file) # change name to include folder no.
fullpath = os.path.join(root,file)
shutil.copy(fullpath,outDirec)
This returns:
os.rename(file,iterator+file)
OSError: [Errno 2] No such file or directory
I'm not even sure I should be using os.rename. I just want to pull out files == 'junk' and copy them to one directory but they all have the exact same name. So I really just need to rename them so they can exist in the same directory. Any help?
Update
for root, dirs,files in os.walk(inDirec):
for file in files:
if file =='junk'
d = os.path.split(root)[1]
filename, iterator = os.path.splitext(d) # folder no. captured
it = iterator[-1] # iterator began with a '.'
shutil.copy(os.path.join(root,file),os.path.join(outDirec,it+file))
Your problem is that your program is using the working directory at launch for your rename operation. You need to provide full relative or absolute paths as arguments to os.rename().
Replace:
os.rename(file, iterator+file)
fullpath = os.path.join(root,file)
shutil.copy(fullpath,outDirec)
With (if you want to move):
os.rename(os.path.join(root, file), os.path.join(outDirec, iterator+file))
Or with (if you want to copy):
shutil.copy(os.path.join(root, file), os.path.join(outDirec, iterator+file))
NOTE: The destination directory should already exist or you will need code to create it.

Categories

Resources