How to add identifier to file name before extension?

I have a file name: name.ext

I want to do the following:

name + id + '.' + ext for name, ext in filename.split() 

or find the best way to take the file name and add a random 7-digit string to the end before the extension.

Here is what I still have:

 def generate_id(size=7, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def append_id(filename): return (name + '_' + generate_id() + '.' + ext for name, ext in filename.split('.')) 

but he sees this as an expression of a generator, which is not my intended result.

What would be the correct way to write the append_id function?

+12
source share
6 answers

To do this, in one line, you can try:

 def append_id(filename): return "{0}_{2}.{1}".format(*filename.rsplit('.', 1) + [generate_id()]) 

It is not very readable, though.

Most frameworks provide functions for working with file names, and Python is no exception. You should use os.path.splitex :

 def append_id(filename): return "{0}_{2}{1}".format(*os.path.splitext(filename) + (generate_id(),)) 

Please note that the second version needs two additional modifications:

  • splitext returns a tuple, not a list, so we need to wrap the result of generate_id tuple
  • splitext saves the point, so you need to remove it from the format string

However, I would not have a single reader here - see the following answer for more readable solutions.

+15
source

I would suggest something simple and easy - use os.path.splitext , to get the base name and extension and then just combine all the components of the result through str.format .

 import os import random import string def generate_id(size=7, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def append_id(filename): name, ext = os.path.splitext(filename) return "{name}_{uid}{ext}".format(name=name, uid=generate_id(), ext=ext) 

Some test files:

 append_id("hello.txt") append_id("hello") append_id("multiple.dots.in.file") 
+21
source

your answer to one answer with random generation -

map(lambda x :x.split(".")[0] + "_" + hashlib.md5(("%.15f" % time.time())+"_"+''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(5))).hexdigest()[:7]+"."+x.split(".")[1], filenames)

here you can enter filenames in the list

just used a random id generation function that takes time and a random 5 character string md5 and takes the first 7 characters of that.

This is not very readable, but since you asked for a one-line solution, I could not come up with a more complicated way.

+2
source

To fix your generate_id code, you need a list comprehension.

 def generate_id(size=7, chars=string.ascii_uppercase + string.digits): return '_' + ''.join([random.choice(chars) for _ in range(size)]) 

Do you use python to rename files? Instead, you can use a command line program such as pwgen .

 mv $filename ${filename/%.ext/_$(pwgen 6 1).ext} 

If you are writing a file from Python, consider using tempfile.NamedTemporaryFile with the appropriate parameters. (delete = False, dir = ".", prefix = "...", suffix = "...")

+2
source
 def append_id(filename): parts = filename.split('.') return "".join(parts[:-1])+ '_' + generate_id() + '.' + parts[-1] 
+2
source

I needed a simpler version of adding a specific suffix to the .txt file in a Python program, i.e. I needed to add -VOC, -TEX, or -RAN to the file names. For example: the file name is -VOC.txt (for the dictionary file), the file name is -TEX.txt (for plain text or utf8 encoded file) or the file name is -RAN.txt (for translating the TEX file), So, I experimented in Jupyter Notebook with the following solution, and it worked, I got the desired result:

 filename = 'C:/Users/User/Desktop/test4.txt' type(filename) # this is just to check the type of filename, which is a string t = filename.rsplit('.' 1) t # this gives me the list ['C:/Users/User/Desktop/test4.txt'] t[0] # this gives me 'C:/Users/User/Desktop/test4', without the '.txt' # Now I can add the suffix I want to the file name, see below t2 = t[0]+'-VOC' t2 # this gives me 'C:/Users/User/Desktop/test4-VOC', which is the desired file name 

More specifically, I applied the above as follows:

 def new_file(): """ Creates vocabulary file """ global file_name input_file_name = filedialog.asksaveasfilename(initialdir="/", defaultextension='*.txt', filetypes=(("Text Documents", "*.txt"), ("all files", "*.*"))) if input_file_name: file_name = input_file_name.rsplit('.', 1)[0]+'-VOC.txt' # notice this line with open(file_name, 'w', encoding='utf-8') as txt_file: txt_file.write(text_B.get('1.0', END)) 
0
source

All Articles