I am trying to make a log file for my application but when I try to make the file with a variable as the name I get a "FileNotFound" error.
Example:
log_file_name = str("log" + "/" + str(current_time.month) + "/" + str(current_time.day) + "/" + str(current_time.year) + ".txt")
log_txt = open(log_file_name, "a")
This gives me a FileNotFound error like this
Traceback (most recent call last):
File "C:\Users\taco\PycharmProjects\pythonProject\mygame.py", line 7, in <module>
log_txt = open(log_file_name, "a")
FileNotFoundError: [Errno 2] No such file or directory: 'log/8/14/2022.txt'
The below method would give me the same error.
log_txt = open (str("log" + "/" + str(current_time.month) + "/" + str(current_time.day) + "/" + str(current_time.year)) + ".txt", "a")
But if I do something simple like this it creates the file as it should:
log_txt = open("log.txt", "a")
Edit I forgot to add that the same happens above when using "a+" instead of "a"
Firstly, instead of concatenating multiple strings, just use f-string which would make your code look something like this:
log_file_name = f"log/{current_time.month}/{current_time.day}/{current_time.year}.txt")
It does the same thing but is a bit easier on the eyes.
Now to answer your question, the reason you're getting this exception is you're using / to seperate the variables which would trick python into thinking the variables are directories.
To fix this, remove the / in your filename string, so that it would look like this:
f"log{current_time.month}{current_time.day}{current_time.year}.txt"
Related
I'm trying to edit a script I've previously written to generate .lab files (or basically txt files with a .lab extension) as part of a project I'm currently working on. Specifically, what I'm currently working on is to edit the script such that it will be able to handle duplicate filenames. Example: if a file named filename already exists, instead of appending or overwriting the existing file, it would instead create a new file named filename_1.
The script is written as shown below:
for line in reader:
utterance = line[4]
path = line[1].split("/")
folder_name = path[len(path) - 2]
file_name = path[len(path) - 1].split(".")[0]
duplicate_num = 0
# Generate the .lab file
try:
if os.path.isfile(truncated_audio_dir + "/" + folder_name + "/" + file_name + "_cut.lab"):
new_file_name = file_name + "_" + str(duplicate_num)
while os.path.isfile(truncated_audio_dir + "/" + folder_name + "/" + new_file_name + "_cut.lab"):
duplicate_num += 1
new_file_name = file_name + "_" + str(duplicate_num)
print("New File Name: ", new_file_name)
outfile = open(truncated_audio_dir + "/" + folder_name + "/" + file_name + "_cut.lab", "a")
outfile.write(utterance)
outfile.close()
elif not os.path.isfile(truncated_audio_dir + "/" + folder_name + "/" + file_name + "_cut.lab"):
print("Is File")
outfile = open(truncated_audio_dir + "/" + folder_name + "/" + file_name + "_cut.lab", "a")
outfile.write(utterance)
outfile.close()
except FileNotFoundError:
print(truncated_audio_dir + "/" + folder_name + "/" + file_name + "_cut.lab" + " not found")
continue
The issue is that when I try and run the script, the issues I'd been experiencing beforehand still seem to persist. Particularly, the case I'd written to handle duplicates does not seem to trigger at all, instead the program keeps throwing FileNotFoundError exceptions (which I'd originally written to handle the case if there was a directory that didn't exist). I'm suspecting that the FileNotFoundError exception handling I'd originally written is causing the issue, but maybe there may be something else that I may not be aware of. Any help would be gladly appreciated.
(the above code is a majority of the script, but not the complete script; I imported sys, csv, and os and reader refers to a csv that I am reading from)
I am making a program to go through my whole windows drive and index every file.
Here is my code :
import os
import time
cTime = (int(time.time())/3600)
os.makedirs(f"C:\\fileDoucumentation\\{cTime}")
os.chdir(f"C:\\fileDoucumentation\\{cTime}")
numberOfFilesChecked = 0
def documentFile(path):
global numberOfFilesChecked
for i in range(len(path) - 1, -1, -1): #search from the back to the front of
#the file name for the period which marks the extension.
if path[i] == ".":
# the following line is the one that produces an error
fObject = open(f"file of {path[i + 1:]}.txt", "a+")
#we create a file named "file of extension", and we set it to append
# mode
numberOfFilesChecked += 1
print(numberOfFilesChecked)
fObject.write(path + "\n")
#we then write the name of the file being indexed to the file we just
# opened, then add a line break.
fObject.close()
break
def loopThroughDir(path):
try:
for i in os.listdir(path):
if os.path.isdir(path + "\\" + i): #if the path is a folder
loopThroughDir(path + "\\" + i)
else: #if it's a regular file
print(path + "\\" + i)
documentFile(path + "\\" + i)
except PermissionError:
pass
if __name__ == '__main__':
loopThroughDir("C:\\")
print(numberOfFilesChecked)
The problem is, it constantly says that whenever I create a file, it says that it cannot find it, and it raises an exception:
FileNotFoundError: [Errno 2] No such file or directory: 'file of Bin\S-1-5-21-1966573187-186149680-2580014948-1001\$I0SFVU6.txt'!
I am not sure what the issue is, since according to tutorialspoint the file mode "a+" will create a file if it does not exist!
EDIT:
I tried the code without any of the "\" and it worked perfectly... I think that it thought I was trying to create a file in a nonexistent directory, so it raised the error.
I'm trying to write a Python script that renames all duplicate file names recursively (i.e. inside all directories)
I already searched the web and Stack Overflow but I couldn't find any answer...
Here's my code:
#!/usr/bin/env python3.6
import os
import glob
path = os.getcwd()
file_list = []
duplicates={}
# remove filename duplicates
for file_path in glob.glob(path + "/**/*.c", recursive=True):
file = file_path.rsplit('/', 1)[1]
if file not in file_list:
file_list.append(file)
else:
if file in duplicates.keys():
duplicates[file] += 1
lista = []
lista.append(file_path)
os.rename(file_path, file_path.rsplit('/', 1)[:-1] + '/' + str(duplicates[file]) + file)
else:
duplicates[file] = 1
os.rename(file_path, file_path.rsplit('/', 1)[:-1] + '/' + str(duplicates[file]) + file)
And this is the error I'm getting:
Traceback (most recent call last):
File "/home/andre/Development/scripts/removeDuplicates.py", line 22, in <module>
os.rename(file_path, file_path.rsplit('/', 1)[:-1] + '/' + str(duplicates[file]) + file)
TypeError: can only concatenate list (not "str") to list
I know why I'm getting this error, but my question is: Is there a more clever way to do this? I'd also like to rename all duplicate directory names, but I still didn't figure it out...
This may seem trivial, but I can seem to track the error and I am very very new to Python, though not to programming. From reading around on the internet for a bit, I think my problem is that .dat ENVI image file isn't being read as a "describe object". But how do I get it to be read as such? I probably need it to read the header info too, any solutions?
Here is my code:
import arcpy #make sure you run the python associated with ArcGIS
import os
filepath = 'filepath'
filename = 'filename'
band_names = range(1,225)
# Path creation
in_folder = filepath + os.sep + 'ENVI'
out_folder = filepath + os.sep + 'GeoTIFF' # preferably an empty folder
# input multiband raster
in_ENVI = in_folder + filename '.dat'
in_raster = raster(in_ENVI)
index = 0
# get raster information specific to each band
desc = arcpy.Describe(in_raster)
################### THIS IS WHERE I GET THE ERROR ##################
Runtime error
Traceback (most recent call last):
File "<string>", line 23, in <module>
NameError: name 'raster' is not defined
################### SCRIPT TERMINATED ##############################
for band in desc.children:
print band
bandName = band.name
band_path = os.path.join(in_raster, bandName)
dest_path = os.path.join(out_folder, filename '_' + band_names(index) + '.tif')
arcpy.CopyRaster_management(band_path, dest_path, "", "", "", "NONE", "NONE", "")
index = index + 1
Ok so I actually figured it out myself. Here is the code I used. The error was actually not in arcpy.Describe() but in arcpy.CopyRaster_management because I didn't convert band_name[index] to a string.
dest_path = os.path.join(out_folder, filename + str(band_names[index]) + '.tif')
I'm trying to write multiple files to a directory with very little changed in between each file (eg. incremental id numbers) When I try run my program, it fails after writing about 5 files. But when I try it again and re-select the source file, it works. Here's my code:
if not os.path.isdir(self.fDirectory + "/AutoGen" + strftime("%Y-%m-%d %H:%M:%S", gmtime())):
os.mkdir(self.fDirectory + "/AutoGen" + strftime("%Y-%m-%d_%H.%M.%S", gmtime()))
anum = 0
for x in range(len(self.csvdata)-1):
for y in range(len(self.csvdata[x+1])):
self.myRoot.find(self.csvdata[0][y]).text = self.csvdata[x][y]
anum+=1
myTree.write(self.fDirectory + "/AutoGen" + strftime("%Y-%m-%d_%H.%M.%S", gmtime()) + "/" + self.filename + "_" + str(anum) + ".xml")
And here's the error I'm getting:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python32\lib\tkinter\__init__.py", line 1399, in __call__
return self.func(*args)
File "C:\Users\CNash\Documents\XML Generator\XMLGen.py", line 148, in doIt
myTree.write(self.fDirectory + "/AutoGen" + strftime("%Y-%m-%d_%H.%M.%S", gmtime()) + "/" + self.filename + "_" + str(anum) + ".xml")
File "C:\Python32\lib\xml\etree\ElementTree.py", line 836, in write
file = open(file_or_filename, "wb")
IOError: [Errno 2] No such file or directory: 'C:/Users/CNash/Documents/XML Generator/AutoGen2012-07-31_20.23.52/EXuTest_DOCD00140_6.xml'
Any ideas much appreciated!
For one, use os.path.join, it will make your life easier.
And it looks to me that the first and last calls to strftime happen at different times (and you left out an underscore in your first one). The script can't find the directory, because it doesn't exist. One named with a time a few seconds before probably, even suspiciously, does, I bet.
Try replacing your first if-statement with
dirname = os.path.join(self.fDirectory,strftime("AutoGen%Y-%m-%d_%H.%M.%S",gmtime()))
if not os.path.isdir(dirname):
os.mkdir(dirname)
and the last line with:
myTree.write(os.path.join(dirname, self.filename + "_" + str(anum) + ".xml"))