我有一个目录,里面包含许多文件夹和文件。我想编写一个脚本,以查找目录中最新的文件的路径和名称,无论是在其子目录中还是在目录本身中。每当我想运行程序时,都会从VSCode中运行此脚本。之前我有类似这样的代码,但它仅适用于目录中的文件,而不是子目录中的文件。
files = sorted(os.listdir(path), key=os.path.getctime, reverse = True)
for file in files: #Finds most recent file with '.cpp' extension
if ".cpp" in file:
last = file
break
subprocess.call(
["g++", "-std=c++14", path + last]
)
subprocess.call(
["open", path + "./a.out"]
)
以下是终端中 "ls -ltr" 命令的输出结果。最后三行是文件夹。
-rw-r--r--@ 1 tanavya.dimri staff 2182 Mar 23 16:10 UVa_LEDTest.cpp
-rw-r--r--@ 1 tanavya.dimri staff 4217 Mar 23 16:11 OPC_SiruseriMetro.cpp
-rw-r--r--@ 1 tanavya.dimri staff 2645 Mar 23 16:12 UVa_Password.cpp
-rw-r--r--@ 1 tanavya.dimri staff 940 Mar 23 16:13 UVa_8Queens.cpp
-rw-r--r--@ 1 tanavya.dimri staff 1587 Mar 23 20:57 UVa12405_Scarecrow.cpp
-rw-r--r--@ 1 tanavya.dimri staff 3014 Mar 25 19:58 UVa_Zones.cpp
-rw-r--r--@ 1 tanavya.dimri staff 2733 Mar 25 20:07 YogesMM.cpp
-rw-r--r--@ 1 tanavya.dimri staff 1066 Mar 26 22:33 ChefAndTraingles.cpp
-rw-r--r--@ 1 tanavya.dimri staff 993 Mar 27 07:10 untitled.cpp
-rw-r--r-- 1 tanavya.dimri staff 33 Mar 27 21:42 out.out
-rwxr-xr-x 1 tanavya.dimri staff 15564 Mar 27 22:54 a.out
drwxr-xr-x 8 tanavya.dimri staff 272 Mar 27 23:35 SpecificAlgorithms
drwxr-xr-x 25 tanavya.dimri staff 850 Mar 30 12:49 DynamicProgramming
drwxr-xr-x 5 tanavya.dimri staff 170 Mar 30 16:27 GraphTheory
也许将来我会在我的子目录中创建更多的子目录,如果有任何建议的脚本在这种情况下也可以使用,那就更加感激了。
编辑:
我喜欢Peter和Jean两位的回答,感谢!我的文件现在是:
import os
import subprocess
path = "/Users/tanavya.dimri/Desktop/CompetitiveProgramming/"
most_recent_file = max((os.path.join(root,f) for root,_,the_files in os.walk(path) for f in the_files if f.lower().endswith(".cpp")),key=os.path.getctime)
subprocess.call(
["g++", "-std=c++14", most_recent_file]
)
run_file = max((os.path.join(root,f) for root,_,the_files in os.walk(path) for f in the_files if f.lower() == "a.out"),key=os.path.getctime)
subprocess.call(
["open", run_file]
)
虽然我也喜欢Peter代码的可读性,但这段代码简短易懂。
os.walk
。 - Peter Wood