I tried to generate a file named, for example, 23-10-2022|21-03-11.xml or if the user enters his own name userGeneratedName23-10-2022-21-03-11.xml. I don't know why when I tried to specify a particular folder where the generated file should be saved the program throws me an Invalid argument error. I suspect that I am using join incorrectly, I don't really know how to correct it
if not os.path.exists("Generated XMLs"):
os.makedirs("Generated XMLs")
#open file
today = date.today()
now = datetime.now()
#if filename is not specified, create file with today's date and time of creation
if filename == "":
filename = today.strftime("%d-%m-%Y") +"|"+ now.strftime("%H-%M-%S")
#if filename is specified,ad at the and of filename today's date and time of creation
else:
filename = filename + today.strftime("%d-%m-%Y")+"|"+ now.strftime("%H-%M-%S")
# open file wchich is in Generated XMLs folder and name it with variable filename
file = open(os.path.join("Generated XMLs", filename + ".xml"), "w")
#write to file
#write header
file.write("\n<root>\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
file.write("\t<POZYCJE>\n")
#write data
# ask user if he wont netto or brutto meters and ad flag
flag = input("Enter 'n' if you want to use netto meters or 'b' if you want to use brutto meters: ")
for i in range(len(convertedData)):
file.write("\t\t<POZYCJA>\n")
file.write("\t\t\t<LP>" + (i+1) + "</LP>\n")
file.write("\t\t\t<TOWAR>\n")
file.write("\t\t\t\t<KOD>" + convertedData[i][0] + " " + convertedData[i][1] + "</KOD>\n")
file.write("\t\t\t\t<NAZWA>" + convertedData[i][0] + " " + convertedData[i][1] + "</NAZWA>\n")
file.write("\t\t\t\t<OPIS/>")
file.write("\t\t\t\t<EAN/>")
file.write("\t\t\t\t<SWW/>")
file.write("\t\t\t\t<NUMER_KATALOGOWY/>")
file.write("\t\t\t\t<MPP>" + "0" + "</MPP>\n")
file.write("\t\t\t</TOWAR>\n")
file.write("\t\t\t<STAWKA_VAT>\n")
file.write("\t\t\t\t<STAWKA>" + "23.00" + "</STAWKA>\n")
file.write("\t\t\t\t<FLAGA>" + "2" + "</FLAGA>\n")
file.write("\t\t\t\t<ZRODLOWA>" + "0.00" + "</ZRODLOWA>\n")
file.write("\t\t\t</STAWKA_VAT>\n")
file.write("\t\t\t<CENY>\n")
file.write("\t\t\t\t<CENAZCZTEREMAMIEJSCAMI>0</CENAZCZTEREMAMIEJSCAMI>\n")
file.write("\t\t\t\t<POCZATKOWA_WAL_CENNIKA>00.0000</POCZATKOWA_WAL_CENNIKA>\n")
file.write("\t\t\t\t<POCZATKOWA_WAL_DOKUMENTU>00.0000</POCZATKOWA_WAL_DOKUMENTU>\n")
file.write("\t\t\t\t<PO_RABACIE_WAL_CENNIKA>00.0000</PO_RABACIE_WAL_CENNIKA>\n")
file.write("\t\t\t\t<PO_RABACIE_PLN>00.0000</PO_RABACIE_PLN>\n")
file.write("\t\t\t\t<PO_RABACIE_WAL_DOKUMENTU>00.0000</PO_RABACIE_WAL_DOKUMENTU>\n")
file.write("\t\t\t</CENY>\n")
file.write("\t\t\t<WALUTA>\n")
file.write("\t\t\t\t<SYMBOL>PLN</SYMBOL>\n")
file.write("\t\t\t\t<KURS_L>1.00</KURS_L>\n")
file.write("\t\t\t\t<KURS_M>1</KURS_M>\n")
file.write("\t\t\t</WALUTA>\n")
file.write("\t\t\t<RABAT>0.00</RABAT>\n")
file.write("\t\t\t<WARTOSC_NETTO>0.00</WARTOSC_NETTO>\n")
file.write("\t\t\t<WARTOSC_BRUTTO>0.00</WARTOSC_BRUTTO>\n")
file.write("\t\t\t<WARTOSC_NETTO_WAL>00.00</WARTOSC_NETTO_WAL>\n")
file.write("\t\t\t<WARTOSC_BRUTTO_WAL>833.94</WARTOSC_BRUTTO_WAL>\n")
if flag == "n":
file.write("\t\t\t<ILOSC>" + convertedData[i][3] + "00" + "</ilosc>\n")
elif flag == "b":
file.write("\t\t\t<ILOSC>" + convertedData[i][2] + "00" + "</ilosc>\n")
else:
print("Error: Wrong flag. Enter 'n' or 'b'.")
file.write("\t\t\t<JB>" + convertedData[i][4] + "</JB>\n")
file.write("\t\t\t<JM_CALKOWITE>0.00</JM_CALKOWITE>\n")
file.write("\t\t\t<JM_ZLOZONA>\n")
file.write("\t\t\t\t\n")
file.write("\t\t\t\t\n")
file.write("\t\t\t\t\n")
file.write("\t\t\t</JM_ZLOZONA>\n")
file.write("\t\t\t<JMZ>" + convertedData[i][4] + "</JMZ>\n")
file.write("\t\t\t<JM_PRZELICZNIK_L>1.00</JM_PRZELICZNIK_L>\n")
file.write("\t\t\t<JM_PRZELICZNIK_M>1</JM_PRZELICZNIK_M>\n")
file.write("\t\t</POZYCJA>\n")
#write footer
file.write("\t</POZYCJE>\n")
file.write("</root>")
#close file
file.close()
The exact error I get:
Traceback (most recent call last):
File "C:\Users\reczul\PycharmProjects\pythonProject5\main.py", line 23, in <module>
main()
File "C:\Users\reczul\PycharmProjects\pythonProject5\main.py", line 13, in main
XMLCreator.CreateXML(DataConverter.ConvertData(data))
File "C:\Users\reczul\PycharmProjects\pythonProject5\venv\Functions\XMLCreator.py", line 20, in CreateXML
file = open(os.path.join("Generated XMLs", filename + ".xml"), "w")
OSError: [Errno 22] Invalid argument: 'Generated XMLs\\24-10-2022|09-23-45.xml'
Process finished with exit code 1
I can not use "|" also I had to convert filename to str.
if not os.path.exists("Generated XMLs"):
os.makedirs("Generated XMLs")
#open file
today = date.today()
now = datetime.now()
#if filename is not specified, create file with today's date and time of creation
if filename == "":
filename = today.strftime("%d-%m-%Y") +"--"+ now.strftime("%H-%M-%S")
#if filename is specified,ad at the and of filename today's date and time of creation
else:
filename = filename + today.strftime("%d-%m-%Y")+"--"+ now.strftime("%H-%M-%S")
filename = str(filename)
# open file wchich is in Generated XMLs folder and name it with variable filename
#file = open(os.path.join(os.path.dirname(os.path.abspath(__file__)),"Generated XMLs",filename + ".xml"), "w")
#cerate XML file which is in Generated XMLs folder
file = open(os.path.join("Generated XMLs", filename + ".xml"), "w")
Related
I GOT THE ANSWER OF M POST THANKS FOR HELPING ME AND WISH OTHERS LEARN FROM MY MISTAKES GOOD LUCK ALL
I Have Folders that take in .meta files and want to save each filename in variable ,
all folder take in the same meta file name but I added the folder name into the file with hypthen means
-> foldername + '-' + filename
and want to print the file name in each folder into file that I created in specific driver and used os.chdir() to load into file path
so when im going to print each folder meta file name into this file its not saving the var
for dirpath, dirnames, files in os.walk('.') :
print('loop')
for file in files :
print('file')
if file.endswith('.meta'):
print('meta')
METAPath = os.path.abspath(os.path.join(dirpath, file))
METABase = os.path.basename(dirpath)
if True :
if file.startswith(METABase + '-' + 'handling'):
HandlingFile = "'" + file + "'"
return HandlingFile
elif file.startswith(METABase + '-' + 'vehicles'):
VehiclesFile = "'" + file + "'"
return VehiclesFile
elif file.startswith(METABase + '-' + 'carvariations'):
CarVariationsFile = "'" + file + "'"
return CarVariationsFile
elif file.startswith(METABase + '-' + 'carcols'):
CarcolsFile = "'" + file + "'"
return CarcolsFile
elif file.startswith(METABase + '-' + 'dlctext'):
DLCTextFile = "'" + file + "'"
return DLCTextFile
print(HandlingFile, VehiclesFile ,CarVariationsFile ,CarcolsFile ,DLCTextFile)
Error :
Traceback (most recent call last):
File "D:\pythonEx\MyFiveMPython\test.py", line 220, in <module>
Stress_Veh()
File "D:\pythonEx\MyFiveMPython\test.py", line 213, in Stress_Veh
print(HandlingFile, VehiclesFile ,CarVariationsFile ,CarcolsFile ,DLCTextFile)
NameError: name 'HandlingFile' is not defined
delete these five statements. They're the source of your error, and they don't do anything.
HandlingFile = HandlingFile
VehiclesFile = VehiclesFile
CarVariationsFile = CarVariationsFile
CarcolsFile = CarcolsFile
DLCTextFile = DLCTextFile
To cut down your code a bit...
if file.startswith(...):
HandlingFile = <some stuff>
return HandlingFile
print(HandlingFile...)
When your "if" statement returns False, HandlingFile is never defined.
Aaah! Now I understand what those extra five statements were trying to do... you were trying to initalize your variables. You didn't want to do
HandlingFile = HandlingFile
you wanted
HandlingFile = None # or False, or '' or something else
I am making a calendar system in python that creates a file with a description as its contents. That file will be placed into a directory with files with the same date to allow for detection of overlapping events.
I have attempted to use shutil to move the file in once created but I am having no luck as well as setting the directory to the new folder. (Apologies for the poor coding, I am new to python and haven't quite got to grips with formatting and the best way to solve these logical problems).
def newEvent(): # Creates new event
directory = input("Input the calender directory. This can be changed in the settings: ")
pattern = "^(3[01]|[12][0-9]|0[1-9]).(1[0-2]|0[1-9]).[0-9]{4}$" # DD.MM.YYY Pattern
eventName = input("Please enter the name of the event: ")
print("'" + eventName + "'" + " successfully Registered.")
time.sleep(0.5)
eventDate = input("Please enter the date of the event in the 'DD.MM.YYYY' format: ")
time.sleep(0.5)
if re.match(pattern, eventDate): # Matches pattern with eventDate
print(eventName + " successfully Registered on the " + eventDate)
time.sleep(0.5)
description = input("Please input a description for the event: ")
time.sleep(0.5)
if os.path.exists(re.sub('\.', '', eventDate)):
fileName = str(re.sub('\.', '', eventDate)) + "/" + eventDate + " - " + eventName + ".txt" # Creates the file name
newFile = open(str(fileName), "w+") # Creates the file
newFile.write(description) # Adds description
newFile.close()
else:
newDir = os.mkdir((re.sub('\.', '', eventDate))) # Creates new directory named the event date minus the "."
fileName = "/" + eventDate + " - " + eventName + ".txt"
newFile = open(str(directory) + (fileName), "w+")
newFile.write(description)
newFile.close()
shutil.move(str(newFile), str(newDir))
print("Your event: " + str(eventName) + " taking place on the " + eventDate + " has been registered. Returning to menu.")
time.sleep(0.5)
menu()
else:
print("Date not valid, returning to 'New Event'.")
time.sleep(0.5)
newEvent()
I would like the code to move the newFile into the created directory but it creates the file in the directory of the .py file.
The problem is with the definition of the paths.
Also you're trying to move newFile which is a TextWrapper instance and not a path string or path-like object (but you convert it to string so the terminal doesn't give you the right error message)
I suggest you to use os.path.join to create the paths: it's more clean, less error prone, and multi-platform so that you don't have to worry between windows and linux path separator (\ or /)
Moreover, you can directly define your filename with the correct absolute path, so that you don't have to move anything
def newEvent(): # Creates new event
directory = input("Input the calender directory. This can be changed in the settings: ")
pattern = "^(3[01]|[12][0-9]|0[1-9]).(1[0-2]|0[1-9]).[0-9]{4}$" # DD.MM.YYY Pattern
eventName = input("Please enter the name of the event: ")
print("'" + eventName + "'" + " successfully Registered.")
time.sleep(0.5)
eventDate = input("Please enter the date of the event in the 'DD.MM.YYYY' format: ")
time.sleep(0.5)
if re.match(pattern, eventDate): # Matches pattern with eventDate
print(eventName + " successfully Registered on the " + eventDate)
time.sleep(0.5)
description = input("Please input a description for the event: ")
time.sleep(0.5)
event_dir = os.path.join(directory, re.sub('\.', '', eventDate))
fileName = os.path.join(directory, event_dir, eventDate + " - " + eventName + ".txt") # Creates the file name
if os.path.exists(event_dir):
newFile = open(str(fileName), "w+") # Creates the file
newFile.write(description) # Adds description
newFile.close()
else:
newDir = os.mkdir(event_dir) # Creates new directory named the event date minus the "."
newFile = open(fileName, "w+")
newFile.write(description)
newFile.close()
# shutil.move(str(fileName), str(newDir))
print("Your event: " + str(eventName) + " taking place on the " + eventDate + " has been registered. Returning to menu.")
time.sleep(0.5)
menu()
else:
print("Date not valid, returning to 'New Event'.")
time.sleep(0.5)
newEvent()
I am running the following block of code to create the path to a new file:
# Opens/create the file that will be created
device_name = target_device["host"].split('.')
path = "/home/user/test_scripts/configs/" + device_name[-1] + "/"
print(path)
# Check if path exists
if not os.path.exists(path):
os.makedirs(path)
# file = open(time_now + "_" + target_device["host"] + "_config.txt", "w")
file = open(path + time_now + "_" + device_name[0] + "_config.txt", "w")
# Time Stamp File
file.write('\n Create on ' + now.strftime("%Y-%m-%d") +
' at ' + now.strftime("%H:%M:%S") + ' GMT\n')
# Writes output to file
file.write(output)
# Close file
file.close()
The code run as intended with the exception that it creates and saves the files on the directory: /home/user/test_scripts/configs/ instead on the indented one that should be: /home/user/test_scripts/configs/device_name[-1]/.
Please advise.
Regards,
./daq
Try using os.path.join(base_path, new_path) [Reference] instead of string concatenation. For example:
path = os.path.join("/home/user/test_scripts/configs/", device_name[-1])
os.makedirs(path, exist_ok=True)
new_name = time_now + "_" + device_name[0] + "_config.txt"
with open(os.path.join(path, new_name), "w+") as file:
file.write("something")
Although I don't get why you're creating a directory with device_name[-1] and as a file name using device_name[0].
I have created a program to merge TIFs into multipage tifs with an rather old version of FreeImagePy from 2009. It actually works pretty well but I have one little hitch. As best I can tell it's not freeing up the memory and eventually crashes. Can anyone tell me what I am missing?
Using Ptyhon 2.7.
import urllib
import FreeImagePy as FIPY
import os.path
import time
# set source files
sourceFile = open('C:\\temp\AGetStatePlats\\PlatsGenesee.csv','r')
# logfile currently gets totally replaced at each run
logFile = open('C:\\temp\\AGetStatePlats\\PlatTifMerge.txt','w')
sourcePath = "c:\\temp\subdownload2\\"
destPath = 'C:\\temp\\subtifMerge\\'
for row in sourceFile:
# prepare filenames
subPath = row.split(',',1)[0]
platID = subPath.split('/',1)[1]
curDocument = sourcePath + platID + '01.tif'
curPage = 0
# check if base file is out there
if not os.path.isfile(destPath + platID + '.tif'):
outImage = FIPY.Image()
outImage.new(multiBitmap = destPath + platID +'.tif')
print (destPath + platID +'.tif')
for n in range (1,100):
#build n
nPad = "{:0>2}".format(n)
if os.path.isfile(sourcePath + platID + nPad + '.tif'):
# delay in case file system is not keeping up may not be needed
time.sleep (1.0/4.0)
outImage.appendPage(sourcePath + platID + nPad + '.tif')
curPage = curPage + 1
else:
outImage.deletePage(0)
outImage.close()
del outImage
logFile.write(sourcePath + platID + '.tif' + '\r')
logFile.write(platID + " PageCount = " + str(curPage) + '\r' )
break
else:
logFile.write(platID + " already exists" + '\r')
# cleanup
sourceFile.close()
logFile.close()
print("Run Complete!")
Here's the error messages:
C:\temp\subtifMerge\05848.tif ('Error returned. ', 'TIFF', 'Warning: parsing error. Image may be incomplete or contain invalid data !') Traceback (most recent call last): File "C:\temp\AGetStatePlats\PlatTIFcombine.py", line 43, in outImage.appendPage(sourcePath + platID + nPad + '.tif') File "C:\Python27\ArcGIS10.4\lib\site-packages\FreeImagePy\FreeIm??agePy.py", line 2048, in appendPage bitmap = self.genericLoader(fileName) File "C:\Python27\ArcGIS10.4\lib\site-packages\FreeImagePy\FreeIm??agePy.py", line 1494, in genericLoader dib = self.Load(fif, fileName, flag); File "C:\Python27\ArcGIS10.4\lib\site-packages\FreeImagePy\FreeIm??agePy.py", line 188, in Load return self.__lib.Load(typ, fileName, flags)
WindowsError: exception: priviledged instruction >>>
I have a Python routine which archives file recordings into a GZipped tarball. The output file appears to be far larger than the source files, and I cannot work out why. As an example of the scale of the issue, 6GB of call recordings are generating an archive of 10GB.
There appear to be no errors in the script and the output .gz file is readable and appears OK apart from the huge size.
Excerpt from my script as follows:
# construct tar filename and open file
client_fileid = client_id + "_" + dt.datetime.now().strftime("%Y%m%d_%H%M%S")
tarname = tar_path + "/" + client_fileid + ".tar.gz"
print "Opening tar file %s " % (tarname), "\n"
try:
tar = tarfile.open (tarname, "w:gz")
except:
print "Error opening tar file: %s" % sys.exc_info()[0]
sql="""SELECT number, er.id, e.id, flow, filename, filesize, unread, er.cr_date, callerid,
length, callid, info, party FROM extension_recording er, extension e, client c
WHERE er.extension_id = e.id AND e.client_id = c.id AND c.parent_client_id = %s
AND DATE(er.cr_date) BETWEEN '%s' AND '%s'""" % (client_id, start_date, end_date)
rows = cur.execute(sql)
recordings = cur.fetchall()
if rows == 0: sys.exit("No recordings for selected date range - exiting")
for recording in recordings: # loop through recordings cursor
try:
ext_len = len(str(recording[0]))
# add preceding zeroes if the ext no starts with 0 or 00
if ext_len == 2: extension_no = "0" + str(recording[0])
elif ext_len == 1: extension_no = "00" + str(recording[0])
else: extension_no = str(recording[0])
filename = recording[4]
extended_no = client_id + "*%s" % (extension_no)
sourcedir = recording_path + "/" + extended_no
tardir = extended_no + "/" + filename
complete_name = sourcedir + "/" + filename
tar.add(complete_name, arcname=tardir) # add to tar archive
except:
print "Error '%s' writing to tar file %s" % (sys.exc_info()[1], csvfullfilename)