how to not overwrite file in python in different os path - python

so i want to avoid overwrite the file name that existed. but i don't know how to combine the code with mycode. please help me
here's my code for write file:
def filepass(f):
print(f)
with open ('media/pass/'+'filepass.txt', 'a') as fo:
fo.write(f)
fo.close()
return fo
and here's the code to create number in name filepass:
def build_filename(name, num=0):
root, ext = os.path.splitext(name)
print(root)
return '%s%d%s' % (root, num, ext) if num else name
def find_next_filename(name, max_tries=20):
if not os.path.exists(name): return name
else:
for i in range(max_tries):
test_name = build_filename(name, i+1)
if not os.path.exists(test_name): return test_name
return None
all i want is to create filename : filepass.txt, filepass1.txt, filepass2.txt

Something like this?
def filepass(f):
print(f)
filename = find_next_filename('media/pass/filepass.txt')
with open (filename, 'a') as fo:
fo.write(f)
# you don't need to close when you use "with open";
# but then it doesn't make sense to return a closed file handle
# maybe let's return the filename instead
return filename

Related

Appending csv, no overwritting

How can I append a csv file with new information without overwritting the existing results? I tried but it overwrites:
def save_jobs_to_excel(jobs_list, filename):
path=r'\Users\Alberto\OneDrive\Documents\Big Data\pirple\jobs'
jobs = pd.DataFrame(jobs_list)
if filename not in path:
jobs.to_csv(os.path.join(path,f'{filename}.csv'))
elif filename in path:
with open(filename,'a') as f:
f.write(jobs.to_csv(os.path.join(path,f'{filename}.csv')))
else:
pass
I think you are double opening your file and then having jobs.to_csv() overwrite. Maybe something like:
def save_jobs_to_excel(jobs_list, filename):
path = r'\Users\Alberto\OneDrive\Documents\Big Data\pirple\jobs'
jobs = pd.DataFrame(jobs_list)
filepath = os.path.join(path,f'{filename}.csv')
if filepath.exists():
jobs.to_csv(filepath)
elif filename in path:
jobs.to_csv(open(filepath,'a'))
else:
pass

Class for file creation and directory validation

After reading some texts regarding creation of files under python, i decided to create this class which creates a new file on a directory, and creating a backup on the other directory if the file already exists (and if it's older than x hours )
The main reason i opened this question is to know if this is a correct way to write a class using try/except correctly, because actually i'm getting a little confused about the preference of using try/except instead if/elses.
Bellow, the working example:
import os
import datetime
class CreateXML():
def __init__(self, path, filename):
self.path = path
self.bkp_path = "%s\\backup" % path
self.filename = filename
self.bkp_file = "%s.previous" % filename
self.create_check = datetime.datetime.now()-datetime.timedelta(hours=-8)
#staticmethod
def create_dir(path):
try:
os.makedirs(path)
return True
except:
return False
#staticmethod
def file_check(file):
try:
open(file)
return True
except:
return False
def create_file(self, target_dir, target_file):
try:
target = "%s\\%s" % (target_dir, target_file)
open(target, 'w')
except:
return False
def start_creation(self):
try:
# Check if file exists
if self.file_check("%s\\%s" % (self.path, self.filename)):
self.create_dir(self.bkp_path)
creation = os.path.getmtime("%s\\%s" % (self.path, self.filename))
fcdata = datetime.datetime.fromtimestamp(creation)
# File exists and its older than 8 hours
if fcdata < self.create_check:
bkp_file_path = "%s\\%s " % (self.bkp_path, self.bkp_file)
new_file_path = "%s\\%s " % (self.path, self.filename)
# If backup file exists, erase current backup file
# Move existing file to backup and create new file.
if self.file_check("%s\\%s" % (self.bkp_path, self.bkp_file)):
os.remove(bkp_file_path)
os.rename(new_file_path, bkp_file_path)
self.create_file(self.bkp_path, self.bkp_file)
#No backup file, create new one.
else:
self.create_file(self.bkp_path, self.bkp_file)
else:
# Fresh creation
self.create_dir(self.path)
self.create_file(self.path, self.filename)
except OSError, e:
print e
if __name__ == '__main__':
path = 'c:\\tempdata'
filename = 'somefile.txt'
cx = CreateXML(path, filename)
cx.start_creation()
So, basically the real question here is:
-With the example above, the usage of try/except is correct?
-It's correct to perform the validations using try/except to check if file or directory allready exists? instead using a simplified version like this one:
import os
# Simple method of doing it
path = 'c:\\tempdata'
filename = 'somefile.txt'
bkp_path = 'c:\\tempdata\\backup'
bkp_file = 'somefile.txt.bkp'
new_file_path = "%s\\%s" % (path, filename)
bkp_file_path = "%s\\%s" % (bkp_path, bkp_file)
if not os.path.exists(path):
print "create path"
os.makedirs(bkp_path)
if not os.path.isfile(new_file_path):
print "create new file"
open(new_file_path, 'w')
else:
print"file exists, moving to backup folder"
#check if backup file exists
if not os.path.isfile(bkp_file_path):
print "New backup file created"
open(bkp_file_path, 'w')
else:
print "backup exists, removing backup, backup the current, and creating newfile"
os.remove(bkp_file_path)
os.rename(new_file_path, bkp_file_path)
open(bkp_file_path, 'w')
-If the usage of try/except is correct, its recomended write an a big class to create a file if it's possible to write a short version of it?
Please do not close this tread, since i'm really confused about what is the "most correct pythonic way to do it".
Thanks in advance.

python unzip files below the root folder

i would like to unzip all the folders and files of an archive below the root folder, i have archive named abc.zip which gives me files as abc/xyz/ abc/123.jpg abc/xyz1/ , i just want to extract xyz/ , 123.jpg and xyz1/ in the CWD
i use below code to extract a file, but would need help on how to omit the root folder of the list
def unzip_artifact( local_directory, file_path ):
fileName, ext = os.path.splitext( file_path )
if ext == ".zip":
Downloadfile = basename(fileName) + ext
print 'unzipping file ' + Downloadfile
try:
zipfile.ZipFile(file_path).extractall(local_directory)
except zipfile.error, e:
print "Bad zipfile: %s" % (e)
return
You have to use a more complex (and therefore more customizable) way to unzip. Instead of using the 'extractall' method, you must extract each files separately with the 'extract' method. Then you will be able to change the destination directory, omitting archive's sub-directories.
Here is your code with the modification you needed :
def unzip_artifact( local_directory, file_path ):
fileName, ext = os.path.splitext( file_path )
if ext == ".zip":
Downloadfile = fileName + ext
print 'unzipping file ' + Downloadfile
try:
#zipfile.ZipFile(file_path).extractall(local_directory) # Old way
# Open the zip
with zipfile.ZipFile(file_path) as zf:
# For each members of the archive
for member in zf.infolist():
# If it's a directory, continue
if member.filename[-1] == '/': continue
# Else write its content to the root
with open(local_directory+'/'+os.path.basename(member.filename), "w") as outfile:
outfile.write(zf.read(member))
except zipfile.error, e:
print "Bad zipfile: %s" % (e)
return

Whats the best way to write python code into a python file?

I want to write a script (generate_script.py) generating another python script (filegenerated.py)
So far i have created generate_script.py:
import os
filepath = os.getcwd()
def MakeFile(file_name):
temp_path = filepath + file_name
file = open(file_name, 'w')
file.write('def print_success():')
file.write(' print "sucesss"')
file.close()
print 'Execution completed.'
The file (filegenerated.py) looks now like this:
def print_success(): print "sucesss"
Now i don't want to manually insert all linebreaks (also due to operating system difficulties)...is there a template system i can use writing python code into a python file? Does someone have an example?
Thanks a lot!
You could just use a multiline string:
import os
filepath = os.getcwd()
def MakeFile(file_name):
temp_path = filepath + file_name
with open(file_name, 'w') as f:
f.write('''\
def print_success():
print "sucesss"
''')
print 'Execution completed.'
If you like your template code to be indented along with the rest of your code, but dedented when written to a separate file, you could use textwrap.dedent:
import os
import textwrap
filepath = os.getcwd()
def MakeFile(file_name):
temp_path = filepath + file_name
with open(file_name, 'w') as f:
f.write(textwrap.dedent('''\
def print_success():
print "sucesss"
'''))
print 'Execution completed.'
lines = []
lines.append('def print_success():')
lines.append(' print "sucesss"')
"\n".join(lines)
If you're building something complex dynamically:
class CodeBlock():
def __init__(self, head, block):
self.head = head
self.block = block
def __str__(self, indent=""):
result = indent + self.head + ":\n"
indent += " "
for block in self.block:
if isinstance(block, CodeBlock):
result += block.__str__(indent)
else:
result += indent + block + "\n"
return result
You could add some extra methods, to add new lines to the block and all that stuff, but I think you get the idea..
Example:
ifblock = CodeBlock('if x>0', ['print x', 'print "Finished."'])
block = CodeBlock('def print_success(x)', [ifblock, 'print "Def finished"'])
print block
Output:
def print_success(x):
if x>0:
print x
print "Finished."
print "Def finished."
Try using \n and \t
import os
filepath = os.getcwd()
def MakeFile(file_name):
temp_path = filepath + file_name
file = open(file_name, 'w')
file.write('def print_success():\n')
file.write('\tprint "sucesss"')
file.close()
print 'Execution completed.'
to output
def print_success():
print "sucesss"
or multiline
import os
filepath = os.getcwd()
def MakeFile(file_name):
temp_path = filepath + file_name
file = open(file_name, 'w')
file.write('''
def print_success():
print "sucesss"
''')
file.close()
print 'Execution completed.'
untubu answer is probably the more pythonic answer, but in your code example you're missing new line chars and tabs.
file.write("def print_success():\n")
file.write('\tprint "success"\n\n')
This will give you the spacing and newlines. The link below will give you some tips on the accepted ones.
http://docs.python.org/release/2.5.2/ref/strings.html

Python / Function parameters

Main objective:
function to read top score from text file.
Parameters to be passed onto function:
A text document!
def highscore():
try:
text_file = open ("topscore.txt", "r")
topscore = int(text_file.read())
print topscore
text_file.close()
return topscore
except:
print "Error - no file"
topscore = 0
return topscore
How to add a text file as a parameter?
def highscore(filename):
try:
text_file = open (filename, "r")
Oh, and you should stop putting more code than necessary into your try block. A clean solution would look like this:
def highscore(filename):
if not os.path.isfile(filename):
return 0
with open(filename, 'r') as f:
return int(f.read())
Or, if you prefer to return 0 in any case where reading the file fails:
def highscore(filename):
try:
with open(filename, 'r') as f:
return int(f.read())
except:
return 0
Another option is to provide a keyword argument. That may be useful if, for example, you have old code that uses this function and can't be updated for some strange reason. Keyword arguments can include a default value.
def highscore( filename = "filename.txt" ):
try:
text_file = open (filename, "r")
Then you can call this function as before to use the default value, "filename.txt":
highscore()
Or specify any new filename:
highscore( filename = "otherfile.csv" )
See the python documentation for more information.
http://docs.python.org/tutorial/controlflow.html#default-argument-values
def highscore(filename):
try:
text_file = open(filename, "r")
...
Simply add a variable identifier (e.g.,filename) to your parameter list and then refer to it when you open the file.
Then call your function with the filename you choose.
topscore = highscore("topscore.txt")

Categories