0

Let's say the start.py is located in C:\.

import os
path = "C:\\Users\\Downloads\\00005.tex"
file = open(path,"a+")
file. truncate(0)
file.write("""Hello
        """)
file.close()
os.startfile("C:\\Users\\Downloads\\00005.tex")

In the subdirectory could be some files. For example: 00001.tex, 00002.tex, 00003.tex, 00004.tex. I want first to search in the subdir for the file with the highest number (00004.tex) and create a new one with the next number (00005.tex), write "Hello" and save it in the subdir 00005.tex.
Are the zeros necessary or can i also just name them 1.tex, 2.tex, 3.tex......?

  • 2
    see if this answers your question https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory?rq=1. Once you have the file names in a list, you can find the max of the list, then increment it by one and create the new file and store them. – Joe Ferndz Aug 02 '20 at 18:24
  • The zeros are necessary if you want to sort them lexicographically, because otherwise 11.tex comes before 2.tex. It depends on how you implement your routine to find the highest number – loudmummer Aug 02 '20 at 21:08

2 Answers2

1

Textually, "2" is greater than "100" but of course numerically, its the opposite. The reason for writing files as say, "00002.txt" and "00100.text" is that for files numbered up to 99999, the lexical sorting is the same as the numerical sorting. If you write them as "2.txt" and "100.txt" then you need to change the non-extension part of the name to an integer before sorting.

In your case, since you want the next highest number, you need to convert the filenames to integers so that you can get a maximum and add 1. Since you are converting to an integer anyway, your progam doesn't care whether you prepend zeroes or not.

So the choice is based on external reasons. Is there some reason to make it so that a textual sort works? If not, then the choice is purely random and do whatever you think looks better.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

You can use glob:

import glob, os
os.chdir(r"Path")

files = glob.glob("*.tex")
entries = sorted([int(entry.split(".", 1)[0]) for entry in files])
next_entry = entries[-1]+1

next_entry can be used as a new filename. You can then create a new file with this name and write your new content to that file

Nles
  • 161
  • 4