[英]How can I search in a subdir for a specific file?
Let's say the start.py is located in C:\.假设 start.py 位于 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.
例如: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.
我想首先在子目录中搜索编号最高的文件 (00004.tex) 并创建一个具有下一个编号 (00005.tex) 的新文件,写入“Hello”并将其保存在子目录 00005.tex 中。
Are the zeros necessary or can i also just name them 1.tex, 2.tex, 3.tex......?零是必需的还是我也可以将它们命名为 1.tex、2.tex、3.tex ......?
Textually, "2" is greater than "100" but of course numerically, its the opposite.从文字上看,“2”大于“100”,但当然从数字上看,恰恰相反。 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.
之所以将文件写成“00002.txt”和“00100.text”是因为对于编号最大为99999的文件,词法排序与数字排序相同。 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.
如果你把它们写成“2.txt”和“100.txt”那么你需要在排序之前将名称的非扩展部分更改为integer。
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.在你的情况下,因为你想要下一个最高的数字,你需要将文件名转换为整数,这样你就可以获得最大值并加 1。因为你正在转换为 integer 无论如何,你的程序不关心你是否在前面加上零或不。
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.
如果没有,那么选择纯粹是随机的,做任何你认为看起来更好的事情。
You can use glob:您可以使用 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. next_entry可以用作新文件名。 You can then create a new file with this name and write your new content to that file
然后您可以使用此名称创建一个新文件并将新内容写入该文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.