winerror32 python renaming file - file

Im using FTP connection, after closing connection, i need to work with file. How can I do that?
import ftplib, os, time
host = "ftp_host"
ftp_user = "ftp_user"
ftp_password = "ftp_pass"
filename = "Mon.xlsx"
filename2 = "Monitor9564.xlsx"
os.rename(filename, filename2)
con = ftplib.FTP(host, ftp_user, ftp_password)
f = open(filename2, "rb")
send = con.storbinary("STOR " + filename2, f)
con.close
time.sleep(2)
os.rename(filename2, filename)
But im getting an error
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'Monitor9564.xlsx' -> 'Mon.xlsx'

You didn't close your file handle before attempting to rename your file. You can issue f.close() before your second rename method, or you can let Python deal with proper file handle scopes for you:
# code...
with open(filename2, "rb") as f:
send = con.storbinary("STOR " + filename2, f)
con.close()
os.rename(filename2, filename)
Also, why are you renaming your file only to rename it back to its original name?

Related

Handling Hebrew files and folders with Python 3.4

I used Python 3.4 to create a programm that goes through E-mails and saves specific attachments to a file server.
Each file is saved to a specific destination depending on the sender's E-mail's address.
My problem is that the destination folders and the attachments are both in Hebrew and for a few attachments I get an error that the path does not exsist.
Now that's not possible because It can fail for one attachment but not for the others on the same Mail (the destination folder is decided by the sender's address).
I want to debug the issue but I cannot get python to display the file path it is trying to save correctly. (it's mixed hebrew and english and it always displays the path in a big mess, although it works correctly 95% of the time when the file is being saved to the file server)
So my questions are:
what should I add to this code so that it will proccess Hewbrew correctly?
Should I encode or decode somthing?
Are there characters I should avoid when proccessing the files?
here's the main piece of code that fails:
try:
found_attachments = False
for att in msg.Attachments:
_, extension = split_filename(str(att))
# check if attachment is not inline
if str(att) not in msg.HTMLBody:
if extension in database[sender][TYPES]:
file = create_file(str(att), database[sender][PATH], database[sender][FORMAT], time_stamp)
# This is where the program fails:
att.SaveAsFile(file)
print("Created:", file)
found_attachments = True
if found_attachments:
items_processed.append(msg)
else:
items_no_att.append(msg)
except:
print("Error with attachment: " + str(att) + " , in: " + str(msg))
and the create file function:
def create_file(att, location, format, timestamp):
"""
process an attachment to make it a file
:param att: the name of the attachment
:param location: the path to the file
:param format: the format of the file
:param timestamp: the time and date the attachment was created
:return: return the file created
"""
# create the file by the given format
if format == "":
output_file = location + "\\" + att
else:
# split file to name and type
filename, extension = split_filename(att)
# extract and format the time sent on
time = str(timestamp.time()).replace(":", ".")[:-3]
# extract and format the date sent on
day = str(timestamp.date())
day = day[-2:] + day[4:-2] + day[:4]
# initiate the output file
output_file = format
# add the original file name where needed
output_file = output_file.replace(FILENAME, filename)
# add the sent date where needed
output_file = output_file.replace(DATE, day)
# add the time sent where needed
output_file = output_file.replace(TIME, time)
# add the path and type
output_file = location + "\\" + output_file + "." + extension
print(output_file)
# add an index to the file if necessary and return it
index = get_file_index(output_file)
if index:
filename, extension = split_filename(output_file)
return filename + "(" + str(index) + ")." + extension
else:
return output_file
Thanks in advance, I would be happy to explain more or supply more code if needed.
I found out that the promlem was not using Hebrew. I found that there's a limit on the number of chars that the (path + filename) can hold (255 chars).
The files that failed excided that limit and that caused the problem

Find string in log files and return extra characters

How can I get Python to loop through a directory and find a specific string in each file located within that directory, then output a summary of what it found?
I want to search the long files for the following string:
FIRMWARE_VERSION = "2.15"
Only, the firmware version can be different in each file. So I want the log file to report back with whatever version it finds.
import glob
import os
print("The following list contains the firmware version of each server.\n")
os.chdir( "LOGS\\" )
for file in glob.glob('*.log'):
with open(file) as f:
contents = f.read()
if 'FIRMWARE_VERSION = "' in contents:
print (file + " = ???)
I was thinking I could use something like the following to return the extra characters but it's not working.
file[:+5]
I want the output to look something like this:
server1.web.com = FIRMWARE_VERSION = "2.16"
server2.web.com = FIRMWARE_VERSION = "3.01"
server3.web.com = FIRMWARE_VERSION = "1.26"
server4.web.com = FIRMWARE_VERSION = "4.1"
server5.web.com = FIRMWARE_VERSION = "3.50"
Any suggestions on how I can do this?
You can use regex for grub the text :
import re
for file in glob.glob('*.log'):
with open(file) as f:
contents = f.read()
if 'FIRMWARE_VERSION = "' in contents:
print (file + '='+ re.search(r'FIRMWARE_VERSION ="([\d.]+)"',contents).group(1))
In this case re.search will do the job! with searching the file content based on the following pattern :
r'FIRMWARE_VERSION ="([\d.]+)"'
that find a float number between two double quote!also you can use the following that match anything right after FIRMWARE_VERSIONbetween two double quote.
r'FIRMWARE_VERSION =(".*")'

tKinter: Invalid File Error

Whenever I attempt to save using this code:
def openfile(self):
self.filename = askopenfilename(filetypes=(("Extinction Save files", "*.exis"), ("All files", "*.*")))
def save(self):
try:
if not self.filename:
self.filename = asksaveasfile(mode='w', defaultextension=".exis", filetypes=(("Extinction Save files", "*.exis"), ("All files", "*.*")))
# if not '.exis' in self.filename:
# self.filename += ".exis"
self.filename.close()
with open(self.filename, "w") as file:
file.write(self.compiledata)
except Exception as error:
print(str(error))
def saveas(self):
try:
self.filename = asksaveasfile(mode='w', defaultextension=".exis", filetypes=(("Extinction Save files", "*.exis"), ("All files", "*.*")))
# if not '.exis' in self.filename:
# self.filename += ".exis"
self.filename.close()
with open(self.filename, "w") as file:
file.write(self.compiledata)
except Exception as error:
print(str(error))
def compiledata(self):
char = comboBox.currentText()
health = lineEdit_2.text()
level = lineEdit_3.text()
XP = lineEdit_4.text()
inv = []
for index in range(self.listWidget.count()):
inv.append(self.listWidget.item(index))
return char + '\ninv[' + ', '.split(inv) + '\n]' + health + '\n' + level + '\n' + XP
I get the following error message:
invalid file: <_io.TextIOWrapper name='C:/Users/Joan/Desktop/file.exis' mode='w' encoding='cp1252'>
I have seen one instance on this site where someone had a somewhat similar error message, but the solution did not help me. I just don't understand what I am supposed to do at this point.
Because you use asksaveasfile(), self.filename is not a filename, but an opened file. You then use self.filename.close(), so self.filename becomes a closed file, but open(...) expects a filename.
To get a the filename from the file you can use self.filename.name, so:
with open(self.filename.name, "w") as file:

open(create) non existing file in lua

I'm trying to save a configtable(parsed to string) to a file wich is created just in time.
local cfg_string = table.tostring(cfg_table)
local file_name = ""
local cfg_file = ""
file_name = com:line(nil) -- reads a line of input from user via terminal
file_name = string.format("some_prefix-%s-some_suffix.lua",file_name)
-- file does NOT exist at this line
cfg_file = io.open("/dir/subdir/"..file_name,"w")
-- file now should exist
os.syslog(type(file_name)) -> string
os.syslog(type(cfg_file)) -> nil
os.syslog(type(cfg_string)) -> string
cfg_file:write(cfg_string)
cfg_file:write(cfg_string) throws "attempt to call "write" a nil value".
So hu,.. cfg_file is nil I know, but why? I also tried to io.open() with "a" flag, but this doesn't work too. The directory exists!
Thanks for your help.
Actually, my code is working. The error is thrown because missig write-permission to dir.
Everyone with such Errors should try
handle_name, err = io.open(file,"w")
print(err)

Groovy - create file issue: The filename, directory name or volume label syntax is incorrect

I'm running a script made in Groovy from Soap UI and the script needs to generate lots of files.
Those files have also in the name two numbers from a list (all the combinations in that list are different), and there are 1303 combinations
available and the script generates just 1235 files.
A part of the code is:
filename = groovyUtils.projectPath + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
targetFile.createNewFile();
where $file is actually that part of the file name which include those 2 combinations from that list:
file = "abc" + "-$firstNumer"+"_$secondNumber"
For those file which are not created is a message returned:"The filename, directory name or volume label syntax is incorrect".
I've tried puting another path:
filename = "D:\\rez\\" + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
targetFile.createNewFile();
and also:
File parentFolder = new File("D:\\rez\\");
File targetFile = new File(parentFolder, "$file"+"_OK.txt");
targetFile.createNewFile();
(which I've found here: What are possible reasons for java.io.IOException: "The filename, directory name, or volume label syntax is incorrect")
but nothing worked.
I have no ideea where the problem is. Is strange that 1235 files are created ok, and the rest of them, 68 aren't created at all.
Thanks,
My guess is that some of the files have illegal characters in their paths. Exactly which characters are illegal is platform specific, e.g. on Windows they are
\ / : * ? " < > |
Why don't you log the full path of the file before targetFile.createNewFile(); is called and also log whether this method succeeded or not, e.g.
filename = groovyUtils.projectPath + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
println "attempting to create file: $targetFile"
if (targetFile.createNewFile()) {
println "Successfully created file $targetFile"
} else {
println "Failed to create file $targetFile"
}
When the process is finished, check the logs and I suspect you'll see a common pattern in the ""Failed to create file...." messages
File.createNewFile() returns false when a file or directory with that name already exists. In all other failure cases (security, I/O) it throws an exception.
Evaluate createNewFile()'s return value or, additionally, use the File.exists() method:
File file = new File("foo")
// works the first time
createNewFile(file)
// prints an error message
createNewFile(file)
void createNewFile(File file) {
if (!file.createNewFile()) {
assert file.exists()
println file.getPath() + " already exists."
}
}

Resources