Python: Check if file from list exists, execute function only if it exists
Tag : python , By : user107021
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You have a couple problems in your code. First, chkifexists is returning as soon as it finds an existing file, so it never checks any remaining names; also, if no files are found then the hashcolumn and filepathNum are never set -- giving you the UnboundLocalError. import os, csv
# store file attributes for easy modifications
# format is 'filename': (hashcolumn, filepathNum)
files = {
'A.csv': (7, 5),
'B.csv': (15, 5),
'C.csv': (1, 0),
}
class NoFilesFound(Exception):
"No .csv files were found to clean up"
def chkifexists(somefiles):
# load all three at once, but only yield them if filename
# is found
filesfound = False
for fname, (hashcolumn, filepathNum) in somefiles.items():
if os.path.isfile(fname):
filesfound = True
yield fname, hashcolumn, filepathNum
if not filesfound:
raise NoFilesFound
def removedupes(infile, outfile, hashcolumn, filepathNum):
# this is now a single-run function
r1 = file(infile, 'rb')
r2 = csv.reader(r1)
w1 = file(outfile, 'wb')
w2 = csv.writer(w1)
hashes = set()
for row in r2:
if row[hashcolumn] =="":
w2.writerow(row)
hashes.add(row[hashcolumn])
if row[hashcolumn] not in hashes:
w2.writerow(row)
hashes.add(row[hashcolumn])
w1.close()
r1.close()
def bakcount(origfile1, origfile2):
'''This function creates a .bak file of the original and does a row count
to determine the number of rows removed'''
os.rename(origfile1, origfile1+".bak")
count1 = len(open(origfile1+".bak").readlines())
#print count1
os.rename(origfile2, origfile1)
count2 = len(open(origfile1).readlines())
#print count2
print str(count1 - count2) + " duplicate rows removed from " \
+ str(origfile1) +"!"
def CleanAndPrettify():
print "Removing duplicate rows from input files..."
try:
for fname, hashcolumn, filepathNum in chkifexists(files):
removedupes(
fname,
os.path.splitext(fname)[0] + "2.csv",
hashcolumn,
filepathNum,
)
bakcount (fname, os.path.splitext(fname)[0] + "2.csv")
except NoFilesFound:
print "no files to clean up"
CleanAndPrettify()
def chkifexists(somefiles):
# load all three at once, but only yield them if filename
# is found
for fname, (hashcolumn, filepathNum) in somefiles.items():
if os.path.isfile(fname):
filesfound = True
yield fname, hashcolumn, filepathNum
def CleanAndPrettify():
print "Removing duplicate rows from input files..."
found_files = list(chkifexists(files))
if not found_files:
print "no files to clean up"
else:
for fname, hashcolumn, filepathNum in found_files:
removedupes(...)
bakcount(...)
|
Python check if file exists doesnt work although the file DO exists
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , The reason is probably / in the beginning of '/outputs/topologia_wynik' + str(file_id) + '.top'. It means "outputs" folder should be under the root folder, and in your case it seems to be under the server working directory. Why not pass os.path.join(app.config['OUTPUT_FOLDER'], 'topologia_wynik' + str(file_id) + '.top') to os.path.isfile() as you did with the input file name?
|
Check if a .txt file exists. FileWriter.exists method not working
Date : March 29 2020, 07:55 AM
To fix the issue you can do SOLVED!!! for the hand guys got it working. Appreciate it! , You have compilation error here: FileWriter userData = new FileWriter(fileName);
if (userData.exists())
File userDataFile = new File(fileName);
if (userDataFile.exists())
FileWriter userData = new FileWriter(userDataFile);
userData.write(user + " ");
userData.write(ps);
userData.close();
System.out.println(new File(fileName).getAbsolutePath());
|
VB.NET: XMLWriter() check if directory exists and if file exists, otherwise create them
Tag : .net , By : jedameron
Date : March 29 2020, 07:55 AM
I hope this helps . I am running into a small bug in a vb.net console application I am working with right now. , This should work for you: ' Exctract the directory path
Dim xmlSaveDir=System.IO.Path.GetDirectoryName(xmlSaveLocation)
' Create directory if it doesn't exit
If (Not System.IO.Directory.Exists(xmlSaveDir)) Then
System.IO.Directory.CreateDirectory(xmlSaveDir)
End If
' now, use a file stream for the XmlWriter, this will create or overwrite the file if it exists
Using fs As New FileStream(xmlSaveLocation, FileMode.OpenOrCreate, FileAccess.Write)
Using writer As XmlWriter = XmlWriter.Create(fs)
' use the writer...
' and, when ready, flush and close the XmlWriter
writer.Flush()
writer.Close()
End Using
' flush and close the file stream
fs.Flush()
fs.Close()
End Using
|
Eiffel: void safety, a concise way to test if an object exists and then call its feature
Date : March 29 2020, 07:55 AM
should help you out To avoid code duplication and multiple tests, the following code could be used: l_foo := foo
if not attached l_foo then
create l_foo
foo := l_foo
end
l_foo.bark
|