所以我将一些数据存储在文件夹中作为 .txt ,例如 FRED.txt & BOB.txt ,它在文本文件中包含从1到10中选择的5个随机数,我不知道如何打印他们的名字(按字母顺序)以及最高的随机数。我知道我必须使用 glob 或 os 库,但我不知道该如何使用它们。 到目前为止,我有这个......
import glob, os
dataFile = open("directory_pathway", "r+")
dataFile.read()
# Somehow printing names & highest number here.
dataFile.close()
非常感谢任何帮助。谢谢:))
答案 0 :(得分:0)
import glob, os, re
names = []
path = os.path.join('path_to_dir', '*.txt')
for filename in glob.glob(path):
names.append(filename)
names.sort()
for filename in names:
print(re.search(r'\w+.txt', filename).group(0))
text = open(filename, 'r')
data = text.read().split()
print(max(data, key = int), '\n')
text.close()
raw_input()
答案 1 :(得分:0)
将找到的文件名与glob
,map
内容排序为int并打印文件名f
和max
:
import glob
import os
path = "path/"
for f in sorted(glob.glob(os.path.join(path,"*.txt"))):
with open(os.path.join(path, f)) as fl:
print("Filename: {}\nMax value: {}".format(f, max(map(int, fl))))
map
会返回一个地图对象,因此我们无需创建列表来查找max
,我们一次只能存储一行/一行。
答案 2 :(得分:0)
import os
result_dict = {}
for i in sorted([i for i in os.listdir("/path/to/folder/") if i.endswith(".txt")]):
f = open(i)
a = f.readlines()
num = sorted([int(j.strip()) for j in a])
print num
result_dict[i] = num[-1]
for i,j in sorted(result_dict.items(), key=lambda s: s[0]):
print i,j
答案 3 :(得分:0)
glob
模块仅从输入目录中获取文本文件。for
循环迭代每个文本文件。输入:关注FRED.txt
文件
2
4
6
8
10
代码:
import glob
import os
dir_path = "/home/vivek/Desktop/stackoverflow/input"
text_files = glob.glob(dir_path+"/*.txt")
print "Test Files:", text_files
result = {}
for i in text_files:
# Read file content.
with open(i, 'rb') as fp:
data = fp.read()
max_no = max([int(j) for j in data.split()])
result[os.path.basename(i)] = max_no
#- Sort and print File names.
sorted_file_names = sorted(result.keys())
for i in sorted_file_names:
print "File Name: %s, MAx Random Number: %d"%(i, result[i])
输出:
Test Files: ['/home/vivek/Desktop/stackoverflow/input/AOB.txt', '/home/vivek/Desktop/stackoverflow/input/ABO.txt', '/home/vivek/Desktop/stackoverflow/input/FRED.txt', '/home/vivek/Desktop/stackoverflow/input/BOB.txt']
File Name: ABO.txt, MAx Random Number: 9
File Name: AOB.txt, MAx Random Number: 9
File Name: BOB.txt, MAx Random Number: 9
File Name: FRED.txt, MAx Random Number: 10
vivek@vivek:~/Desktop/stackoverflow/input$
答案 4 :(得分:-1)
sorted(glob.glob("*.txt"))
会为您提供已排序的文件名列表。然后迭代该列表,打开每个文件,并打印任何你喜欢的内容。