使用python读取文本文件并按扩展名排序



我想用python读取一个文本文件。如果找到一个带有.cpp的行,请先处理它,然后如果找到扩展名为.java的行,则处理它第二个

Test.py是我的示例代码,使用for循环,它将读取Test.txt,然后它将首先处理COMPILE_JAVA((方法,然后执行COMPILE_CPP((方法。

Test.txt

/home/jenkins/workspace/a/Hello.java
/home/jenkins/workspace/b/Hello.cpp
/home/jenkins/workspace/b/Hello1.cpp

测试

for f in files:
ACTION1 = False
ACTION2 = False
with open(f, 'r') as file:
for line in (file):
if ACTION1 is False and ('.cpp' in line ):
COMPILE_CPP()
ACTION1 = True
elif ACTION2 is False and '.java' in line:
COMPILE_JAVA()
ACTION2 = True
break

IIUC您可以使用os.path.splitext:对从test.txt读取的列表进行扩展排序

import os
with open(f, 'r') as file:
sorted_files = sorted(file, key=lambda x: os.path.splitext(x)[1])
for line in sorted_files:
# rest of the code

给定

l = ['/home/jenkins/workspace/a/Hello.java',
'/home/jenkins/workspace/b/Hello.cpp',
'/home/jenkins/workspace/b/Hello1.cpp']

然后运行sorted(l, key=lambda x: os.path.splitext(x)[1])返回:

['/home/jenkins/workspace/b/Hello.cpp',
'/home/jenkins/workspace/b/Hello1.cpp',
'/home/jenkins/workspace/a/Hello.java']

说明:

os.path.splitext返回元组(根,ext(,例如os.path.splitext("dir/myfile.txt")返回("dir/myfile", ".txt"),因此lambda x: os.path.splitext(x)[1]返回第二部分(.txt(。

然后将其作为参数传递给sorted函数,以便按扩展名按字母顺序对列表进行排序。

也许这会有所帮助?我使用了冒泡排序来对扩展进行排序。

row_list = []
with open("test.txt", "r") as file:
line = file.readline()
while line:
row_list.append(line)
for i in range(1, len(row_list)):
for j in range(len(row_list), i, -1):
ext1 = row_list[j-1].split(".")[1]
ext2 = row_list[j].split(".")[1]
if ext1 > ext2:
row_list[j-1], row_list[j] = row_list[j], row_list[j-1]
with open("output_file.txt", "w") as file:
for row in row_list:
file.write(f"{row}n")

最新更新