creating a output file when the output file exists in the path - python

How do I code in python the option that when the output file exists in the path, the output file will automatically be "originalname"+"_1" / "originalname"+"_2" and so on ?

Something like
import os.path
def getnewfilename(filename):
testfile = filename
i = 0
while os.path.exists(testfile):
i += 1
testfile = "%s_%s" % (testfile, i)
return testfile
This should generate
filename
filename_1
filename_2
if you use %s_%3i" you should get
filename
filename_001
filename_002
filename_003
which will then list alphabetically (but have problems when i>=1000)

You can use os.path.exists to check if a file already exists. The rest is a simple loop that tries new filenames.

isfile checks for the existence of a file and goes down simlinks as well; you can use the full filepath.
if os.path.isfile(filename):
do_something()

Related

Get name of created file

I'm creating files in python and I want to print the full path of the already file created. Example:
dt = datetime.datetime.now()
datetime = dt.strftime("%d-%m")
output = open("c:\path\to\file_"+datetime+".txt","w")
How can I print the final name of the created file?
I tried:
print (output)
but it gives me a rare string.
For real file objects such as that,
print(output.name)
open() method doesn't return anything relevant. You can try on below methods...
1.print(output.__file__)
2. Import os
os.path.abspath("filename.ext"). # it will add the cwd to file name or if iterating the real path
os.path.dirname("filename.ext")
os.path.dirname("filename.ext")
3. Files= os.listdir(os.getcwd()) # it will list the files in cwd(you can give any path)
for i in files:
print(os.path.abspath(i))

Is there a way to remove part of a file name (path) in python?

I have around 50 files that have their name and then the date they were created at 3 times. How can I remove that part from the file name in python (You can show an example with other data it doesn't really matter)
I tried something like that:
file = 'directory/imagehellohellohello.png'
keyword = 'hello'
if (file.count(keyword) >= 3):
//functionality (here I want to remove the hello's from the file path)
This can be done quite simply using pathlib:
from pathlib import Path
path = Path("directory/imagehellohellohello.png")
target = path.with_name(path.name.replace("hello", ''))
path.rename(target)
And this indeed renames the file to "directory/image.png".
From Python version 3.8 the rename method also returns the new files' path as a Path object. (So it is possible to do:
target = path.rename(path.with_name(path.name.replace("hello", '')))
Methods/attributes used: Path.rename, Path.with_name, Path.name, str.replace
file = 'directory/imagehellohellohello.png'
keyword = 'hello'
if keyword*3 in file:
newname = file.replace(keyword*3, '')
os.rename(file, newname)

Python - create next file

I am writing a small script. The script creates .txt files. I do not want to replace existing files. So what I want python to do is to check if the file already exists. If it does not it can proceed. If the file does exists I would like python to increment the name and than check again if the file already exists. If the file does not already exist python may create it.
EXAMPLE:
current dir has these files in it:
file_001.txt
file_002.txt
I want python to see that the two files exists and make the next file:
file_003.txt
creating files can be done like this:
f = open("file_001.txt", "w")
f.write('something')
f.close()
checking if a file exists:
import os.path
os.path.isfile(fname)
If you want to check whether it's both a file and that it exist then use os.path.exists along with os.path.isfile. Or else just the former seems suffice. Following might help:
import os.path as op
print op.exists(fname) and op.isfile(fname)
or just print op.exists(fname)
Here is some code that will get the job done, I answered it myself.
import os.path
def next_file(filename):
"""
filename: string. Name only of the current file
returns: string. The name of the next file to be created
assumes the padding of the file is filename_001.txt The number of starting zeros does not not matter
"""
fill_exists = True
current = '001'
padding = len(current) # length of digits
file = '{}_{}.txt'.format(filename, current) # the actual name of the file, inlc. extension
while fill_exists:
if not os.path.isfile(file): # if the file does not already exist
f = open(file, 'w') # create file
f.write(filename)
f.close()
return 'Created new file: {}_{}.txt'.format(filename, current) # shows the name of file just created
else:
current = str(int(current)+1).zfill(padding) # try the next number
file = '{}_{}.txt'.format(filename, current)

Matching MD5 Hashes from another script

Ok so i'm trying to create a script that does the following: Searches a directory for known hashes. Here is my first script:
Hash.py
import hashlib
from functools import partial
#call another python script
execfile("knownHashes.py")
def md5sum(filename):
with open(filename, mode='rb') as f:
d = hashlib.md5()
for buf in iter(partial(f.read, 128), b''):
d.update(buf)
return d.hexdigest()
print "Hash of is: "
print(md5sum('photo.jpg'))
if md5List == md5sum:
print "Match"
knownHashes.py
print ("Call worked\n")
md5List = "01071709f67193b295beb7eab6e66646" + "5d41402abc4b2a76b9719d911017c592"
The problem at the moment is that I manually have to type in the file I want to find out the hash of where it says photo.jpg. Also, The I haven't got the md5List to work yet.
I want the script to eventually work like this:
python hash.py <directory>
1 match
cookies.jpg matches hash
So how can I get the script to search a directory rather than manually type in what file to hash? Also, how can I fix the md5List because that is wrong?
You can get a list of files in the current working directory using the following. This is the directory that you run the script from.
import os
#Get list of files in working directory
files_list = os.listdir(os.getcwd())
You can iterate through the list using a for loop:
for file in files_list:
#do something
As equinoxel also mentioned below, you can use os.walk() as well.
Simple little gist should solve most of your problems. Understandable if you don't like using OOP for this problem, but I believe all of the important conceptual pieces are here in a pretty clean, concise representation. Let me know if you have any questions.
class PyGrep:
def __init__(self, directory):
self.directory = directory
def grab_all_files_with_ending(self, file_ending):
"""Will return absolute paths to all files with given file ending in self.directory"""
walk_results = os.walk(self.directory)
file_check = lambda walk: len(walk[2]) > 0
ending_prelim = lambda walk: file_ending in " ".join(walk[2])
relevant_results = (entry for entry in walk_results if file_check(entry) and ending_prelim(entry))
return (self.grab_files_from_os_walk(result, file_ending) for result in relevant_results)
def grab_files_from_os_walk(self, os_walk_tuple, file_ending):
format_check = lambda file_name: file_ending in file_name
directory, subfolders, file_paths = os_walk_tuple
return [os.path.join(directory, file_path) for file_path in file_paths if format_check(file_path)]

Why is my write function not creating a file?

According to all the sources I've read, the open method creates a file or overwrites one with an existing name. However I am trying to use it and i get an error:
File not found - newlist.txt (Access is denied)
I/O operation failed.
I tried to read a file, and couldn't. Are you sure that file exists? If it does exist, did you specify the correct directory/folder?
def getIngredients(path, basename):
ingredient = []
filename = path + '\\' + basename
file = open(filename, "r")
for item in file:
if item.find("name") > -1:
startindex = item.find("name") + 5
endindex = item.find("<//name>") - 7
ingredients = item[startindex:endindex]
ingredient.append(ingredients)
del ingredient[0]
del ingredient[4]
for item in ingredient:
printNow(item)
file2 = open('newlist.txt', 'w+')
for item in ingredient:
file2.write("%s \n" % item)
As you can see i'm trying to write the list i've made into a file, but its not creating it like it should. I've tried all the different modes for the open function and they all give me the same error.
It looks like you do not have write access to the current working directory. You can get the Python working directory with import os; print os.getcwd().
You should then check whether you have write access in this directory. This can be done in Python with
import os
cwd = os.getcwd()
print "Write access granted to current directory", cwd, '>', os.access(cwd, os.W_OK)
If you get False (no write access), then you must put your newfile.txt file somewhere else (maybe at path + '/newfile.txt'?).
Are you certain the directory that you're trying to create the folder in exists?
If it does NOT... Then the OS won't be able to create the file.
This looks like a permissions problem.
either the directory does not exist or your user doesn't have the permissions to write into this directory .
I guess the possible problems may be:
1) You are passing the path and basename as parameters. If you are passing the parameters as strings, then you may get this problem:
For example:
def getIngredients(path, basename):
ingredient = []
filename = path + '\\' + basename
getIngredients("D","newlist.txt")
If you passing the parameters the above way, this means you are doing this
filename = "D" + "\\" + "newlist.txt"
2) You did not include a colon(:) after the path + in the filename.
3) Maybe, the file does not exist.

Categories

Resources