So I have some pieces of data stored in a folder as .txt , eg FRED.txt & BOB.txt , which in the text file contain their 5 random numbers chosen from 1 to 10 and I am stuck as to how I can print their names (in alphabetical order) along with their highest random number. I know that I have to use the glob or os libraries but I don't really know where to go with them. So far I have this...
import glob, os
dataFile = open("directory_pathway", "r+")
dataFile.read()
# Somehow printing names & highest number here.
dataFile.close()
Any help is much appreciated. Thanks :)
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()
sort the file names found with glob
, map
the contents to int and print the filename f
and the 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
returns a map object so we don't need to create a list to find the max
, we only store one line/value at a time.
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
glob
module. for
loop to iterate every text file. input: Following contents in FRED.txt
file
2
4
6
8
10
code:
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])
output:
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$
sorted(glob.glob("*.txt"))
will get you the list of filenames, sorted. Then iterate over that list, open each file, and print whatever you like.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.