TIF to JPEG Conversion - No such file or directory - python

I am using this code (answer by #user2019716) to convert .tif to .jpeg to use on the tensorflow object detection API. I have done the conversion before with no problems, but for some reason today, I receive a No such file or directory: '__0.tif' error and I don't understand why this is happening. I've checked the directory that I put in C:/Users/name/Desktop/phantom80_labelImg/TIF/ and there are a list of .tif files starting from __0.tif to __34.tif. I know the code works because I have used it before, but I don't know why it is not reading file .tif files now.
Any suggestions?
import os
from PIL import Image
for infile in os.listdir("C:/Users/name/Desktop/phantom80_labelImg/TIF/"):
print("file : " + infile)
if infile[-3:] == "tif" or infile[-3:] == "bmp" :
# print "is tif or bmp"
outfile = infile[:-3] + "jpeg"
im = Image.open(infile)
print("new filename : " + outfile)
out = im.convert("RGB")
out.save(outfile, "JPEG", quality=90)
C:\Users\name\anaconda3\envs\MaskRCNN_SpeCraft\python.exe C:/Users/name/z/MaskRCNN_SpeCraft/tif_to_jpeg.py
Traceback (most recent call last):
File "C:/Users/name/z/MaskRCNN_SpeCraft/tif_to_jpeg.py", line 12, in <module>
im = Image.open(infile)
File "C:\Users\name\anaconda3\envs\MaskRCNN_SpeCraft\lib\site-packages\PIL\Image.py", line 2891, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: '__0.tif'
C:\Users\name\z\MaskRCNN_SpeCraft
file : __0.tif
Process finished with exit code 1

os.listdir(dir) only returns names of the files in that directory (documentation).
To open file you will need to get full file path. You can use os.path.join (documentation)
root_dir = "C:/Users/name/Desktop/phantom80_labelImg/TIF/"
for filename in os.lisdir(root_dir):
infile = os.path.join(root_dir, filename)
# rest of your code

Related

Python, Tried making a script which takes all directorys and renames all the files in them

I tried making an python script which gets all directorys then
goes to the directorys and changes all the files name to the directory name.
The error :
Traceback (most recent call last):
File "D:\assets\steamcmd\yus.py", line 24, in <module>
os.rename(OurFilePath, os.path.join(pathy, pathname+str(file_extension)))
FileNotFoundError: [WinError 2] Nie można odnaleźć określonego pliku (cannot find file): 'steamapps\\workshop\\content\\573090\\2138774925\\.crash' -> 'steamapps\\workshop\\content\\573090\\2138774925\\2138774925
Code below which was used :
import os
directory = "steamapps\\workshop\\content\\573090\\"
for f in os.listdir(directory):
files = os.listdir()
pathy = os.path.join(directory, f)
for index,file in enumerate(files):
OurFilePath = os.path.join(pathy, file)
filename, file_extension = os.path.splitext(OurFilePath)
pathname = os.path.basename(pathy)
os.rename(OurFilePath, os.path.join(pathy, pathname+str(file_extension)))
Eventually, i found the error and have fixed the code.
The problem was : I used os.listdir the wrong way.
Heres the fixed code which i used :
directory = "steamapps\\workshop\\content\\573090\\"
for f in os.listdir(directory):
pathy = os.path.join(directory, f)
for file in os.listdir(pathy):
OurFilePath = os.path.join(pathy, file)
filename, file_extension = os.path.splitext(OurFilePath)
pathname = os.path.basename(pathy)
os.rename(os.path.join(os.path.join(directory, f), file), os.path.join(pathy, pathname+str(file_extension)))

Decompressing .bz2 files in a directory in python

I would like to decompress a bunch of .bz2 files contained in a folder (where there are also .zst files). What I am doing is the following:
destination_folder = "/destination_folder_path/"
compressed_files_path="/compressedfiles_folder_path/"
dirListing = os.listdir(compressed_files_path)
for file in dirListing:
if ".bz2" in file:
unpackedfile = bz2.BZ2File(file)
data = unpackedfile.read()
open(destination_folder, 'wb').write(data)
But I keep on getting the following error message:
Traceback (most recent call last):
File "mycode.py", line 34, in <module>
unpackedfile = bz2.BZ2File(file)
File ".../miniconda3/lib/python3.9/bz2.py", line 85, in __init__
self._fp = _builtin_open(filename, mode)
FileNotFoundError: [Errno 2] No such file or directory: 'filename.bz2'
Why do I receive this error?
You must be sure that all the file paths you are using exist.
It is better to use the full path to the file being opened.
import os
import bz2
# this path must exist
destination_folder = "/full_path_to/folder/"
compressed_files_path = "/full_path_to_other/folder/"
# get list with filenames (strings)
dirListing = os.listdir(compressed_files_path)
for file in dirListing:
# ^ this is only filename.ext
if ".bz2" in file:
# concatenation of directory path and filename.bz2
existing_file_path = os.path.join(compressed_files_path, file)
# read the file as you want
unpackedfile = bz2.BZ2File(existing_file_path)
data = unpackedfile.read()
new_file_path = os.path.join(destination_folder, file)
with bz2.open(new_file_path, 'wb') as f:
f.write(data)
You can also use the shutil module to copy or move files.
os.path.exists
os.path.join
shutil
bz2 examples

Extracting zip files using python

I'm trying to get all zip files in a specific directory name "downloaded" and to extract all of their content to a directory named "extracted".
I don't know why, after I'm iterating only existing files name, I get an error that there is no such file...
allFilesList = os.listdir(os.getcwd()+"/downloaded")
print allFilesList #verify - correct expected list
from zipfile import ZipFile
os.chdir(os.getcwd()+"/extracted/")
print os.getcwd() #verify - correct expected dir
for fileName in allFilesList:
print fileName
with ZipFile(fileName, 'r') as zipFileObject:
if os.path.exists(fileName):
print "Skipping extracting " + fileName
continue
zipFileObject.extractall(pwd='hello')
print "Saving extracted file to extracted/",fileName
print "all files has been successfully extracted"
Error message:
File "program.py", line 77, in <module>
with ZipFile(fileName, 'r') as zipFileObject:
File "/usr/lib/python2.7/zipfile.py", line 779, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'zipFile1.zip'
You're getting the list of filenames from one directory, then changing to another, and trying to extract the files from that directory that likely don't exist:
allFilesList = os.listdir(os.getcwd()+"/downloaded")
# ...
os.chdir(os.getcwd()+"/extracted/")
# ...
with ZipFile(fileName, 'r') as zipFileObject:
If you change that file ZipFile command to something like this:
with ZipFile(os.path.join("..", "downloaded", fileName), 'r') as zipFileObject:
You should be able to open the file in the directory you found it in.

Getting a error: FileNotFoundError: [Errno 2] No such file or directory: while trying to open a file

In a Folder called Assignment Parser, I've my parsing.py file along with a auth.txt file. Trying to open this auth.txt file. But getting an error that says :
(base) C:\Users\Ajay\Desktop\Python\Assignment Parser>python parsing.py
Traceback (most recent call last):
File "parsing.py", line 27, in <module>
main()
File "parsing.py", line 8, in main
file = open(file_path / "auth.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Ajay\\Desktop\\Python\\Assignment Parser\\auth.txt'
Code:
from pathlib import Path
import os
def main():
# read file
# C:\Users\Ajay\Desktop\Python\Assignment Parser\
file_path = Path("C:/Users/Ajay/Desktop/Python/Assignment Parser/")
file = open(file_path / "auth.txt","r")
# file = open("auth.txt", "r")
lines = file.readlines()
file.close()
Where is this going wrong? PFA for the screenprint.
Try this:
from pathlib import Path
import os
def main():
# read file
# C:\Users\Ajay\Desktop\Python\Assignment Parser\
file_path = Path("C:/Users/Ajay/Desktop/Python/Assignment Parser/")
file = open(os.path.join(file_path, "auth.txt"), "r")
# file = open("auth.txt", "r")
lines = file.readlines()
file.close()
I think the problem is in file extension, I see parsing has .py extension but auth is not
please try file = open(file_path / "auth", "r") again (just delete .txt extension)
As you have your python file in same folder as your text file. You can directly use below code.
def main():
file = open("./auth.txt")
lines = file.readlines()
file.close()
Also make sure, your syder working directory is set to this folder path "C:/Users/Ajay/Desktop/Python/Assignment Parser"

Creating text file: IOError: [Errno 21] Is a directory: '/Users/muitprogram/PycharmProjects/untitled/HR/train.txt'

I am trying to write to create and write to a text file. However, the error
Traceback (most recent call last):
File "/Users/muitprogram/PycharmProjects/untitled/histogramSet.py", line 207, in <module>
drinktrainfile = open(abs_file_path, "w")
IOError: [Errno 21] Is a directory: '/Users/muitprogram/PycharmProjects/untitled/HR/train.txt'
shows up. There are other instances of this in Stack Overflow, however, none of these deal with creating and writing a new file. The directories all exist however- only the file is being created The code that does this is:
import os
script_path = os.path.abspath(__file__) # i.e. /path/to/dir/foobar.py
script_dir = os.path.split(script_path)[0] # i.e. /path/to/dir/
rel_path = str(j) + "/train.txt" # HR/train.txt
abs_file_path = os.path.join(script_dir, rel_path) #/path/to/dir/HR/train.txt
drinktrainfile = open(abs_file_path, "w")
EDIT: train.txt shows up, except as a directory. How do I make it a text file?
The resource is actually a directory. It was very likely a mistake, as it is not likely that somebody would have created a directory by that name. First, remove that directory, and then try to create and open the file.
You can open the file with open('/Users/muitprogram/PycharmProjects/untitled/HR/train.txt', 'w'), assuming that the file does not already exist.

Categories