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.
Related
I'm having an issue trying to open a file that is definitely saved to my computer ('NYT-bestsellers.txt'), but whenever I try opening it with my code I get the error
FileNotFoundError: [Errno 2] No such file or directory: 'NYT-bestsellers.txt'
I thought about using the method where you use the full path to open the file… but this is part of an assignment that I'll be submitting later this week. If I open the file using a specific path from my laptop, I'm worried that it won't open for the marker. Please advise!
with open('NYT-bestsellers.txt', 'r') as file:
file = file.splitlines()
As Ryan said, every time you open a file by a relative name, you need to make clear for the current work path.
import sys
import os
current_work_directory = os.getcwd() # Return a string representing the current working directory.
print('Current work directory: {}'.format(current_work_directory))
# Make sure it's an absolute path.
abs_work_directory = os.path.abspath(current_work_directory)
print('Current work directory (full path): {}'.format(abs_work_directory))
print()
filename = 'NYT-bestsellers.txt'
# Check whether file exists.
if not os.path.isfile(filename):
# Stop with leaving a note to the user.
print('It seems file "{}" not exists in directory: "{}"'.format(filename, current_work_directory))
sys.exit(1)
# File exists, go on!
with open(filename, 'r') as file:
file = file.splitlines()
If you confirm that the file will be along with your python script file, you can do some preparatory work before opening the file:
script_directory = os.path.split(os.path.abspath(__file__))[0]
print(script_directory)
abs_filename = os.path.join(script_directory, filename)
print(abs_filename)
with open(abs_filename, 'r') as file:
file = file.splitlines()
I'm having trouble working with Python3's tempfile library in general.
I need to write a file in a temporary directory, and make sure it's there. The third party software tool I use sometimes fails so I can't just open the file, I need to verify it's there first using a 'while loop' or other method before just opening it. So I need to search the tmp_dir (using os.listdir() or equivalent).
Specific help/solution and general help would be appreciated in comments.
Thank you.
Small sample code:
import os
import tempfile
with tempfile.TemporaryDirectory() as tmp_dir:
print('tmp dir name', tmp_dir)
# write file to tmp dir
fout = open(tmp_dir + 'file.txt', 'w')
fout.write('test write')
fout.close()
print('file.txt location', tmp_dir + 'lala.fasta')
# working with the file is fine
fin = open(tmp_dir + 'file.txt', 'U')
for line in fin:
print(line)
# but I cannot find the file in the tmp dir like I normally use os.listdir()
for file in os.listdir(tmp_dir):
print('searching in directory')
print(file)
That's expected because the temporary directory name doesn't end with path separator (os.sep, slash or backslash on many systems). So the file is created at the wrong level.
tmp_dir = D:\Users\foo\AppData\Local\Temp\tmpm_x5z4tx
tmp_dir + "file.txt"
=> D:\Users\foo\AppData\Local\Temp\tmpm_x5z4txfile.txt
Instead, join both paths to get a file inside your temporary dir:
fout = open(os.path.join(tmp_dir,'file.txt'), 'w')
note that fin = open(tmp_dir + 'file.txt', 'U') finds the file, that's expected, but it finds it in the same directory where tmp_dir was created.
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.
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.
I'm having trouble creating a directory and then opening/creating/writing into a file in the specified directory. The reason seems unclear to me. I'm using os.mkdir() and
path=chap_name
print "Path : "+chap_path #For debugging purposes
if not os.path.exists(path):
os.mkdir(path)
temp_file=open(path+'/'+img_alt+'.jpg','w')
temp_file.write(buff)
temp_file.close()
print " ... Done"
I get the error
OSError: [Errno 2] No such file or directory: 'Some Path Name'
Path is of the form 'Folder Name with un-escaped spaces'
What am I doing wrong here?
Update: I tried running the code without creating the directory
path=chap_name
print "Path : "+chap_path #For debugging purposes
temp_file=open(img_alt+'.jpg','w')
temp_file.write(buff)
temp_file.close()
print " ... Done"
Still get an error. Confused further.
Update 2:The Problem seems to be the img_alt, it contains a '/' in some cases, which makes is causing the trouble.
So I need to handle the '/'.
Is there anyway to escape the '/' or is deletion the only option?
import os
path = chap_name
if not os.path.exists(path):
os.makedirs(path)
filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:
temp_file.write(buff)
Key point is to use os.makedirs in place of os.mkdir. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html
Open the file in binary mode as you are storing binary (jpeg) data.
In response to Edit 2, if img_alt sometimes has '/' in it:
img_alt = os.path.basename(img_alt)
import os
os.mkdir('directory name') #### this command for creating directory
os.mknod('file name') #### this for creating files
os.system('touch filename') ###this is another method for creating file by using unix commands in os modules