I'm trying to sort the files I'm saving according to their creation / last modification time. It turns out that the files are generated so quickly that their creation date ends up being the same.
For example, let's say I have an array of objects:
data = [
{ "Name": "Kevin Durant", "Team": "Brooklyn Nets" },
{ "Name": "LeBron James", "Team": "Los Angeles Lakers" },
{ "Name": "Trae Young", "Team": "Atlanta Hawks" },
];
I create a directory:
download_folder = os.path.expanduser("~")+"/Downloads/"
dir_name = "NBA"
makedir_path = os.path.join(download_folder, dir_name)
if not os.path.exists(makedir_path):
os.makedirs(makedir_path)
I use a for to save each object in a different file (the name of each file will be the name of the player's team):
for document in data:
file_name = document["Team"] + ".txt"
path = os.path.join(makedir_path, file_name)
open(path, "x")
with open(os.path.join(makedir_path, file_name),'w') as new_f:
json.dump(found_database, new_f, indent=4, sort_keys=True)
After creating the files, I try to order them according to the creation / modification date (which would be the same order as the elements of the array of object):
os.chdir(makedir_path)
files = filter(os.path.isfile, os.listdir(makedir_path))
files = [os.path.join(makedir_path, f) for f in files]
files.sort(key=lambda x: os.path.getmtime(x))
# Another way I tried to order but it didn't work
# files.sort(key=os.path.getctime)
But, instead, the files are ordered by the file name (team name):
I want it to be ordered by the same array order. So I would have this:
Brooklyn Nets.txt
Los Angeles Lakers.txt
Atlanta Hawks.txt
Is that even possible, or the OS itself sorts it by its name by default? Thank you!
Well, I don't think there is anything you can easily do with your OS for that.
However, I can propose based on your array:
import glob
import os
data = [
{ "Name": "Kevin Durant", "Team": "Brooklyn Nets" },
{ "Name": "LeBron James", "Team": "Los Angeles Lakers" },
{ "Name": "Trae Young", "Team": "Atlanta Hawks" },
]
for filename in glob.glob("*txt"):
name = filename.split(".")[0]
for i, dat in enumerate(data):
if dat['Team'] == name:
os.rename(filename,str(i)+"_"+filename.replace(" ","_"))
print (str(i)+"_"+filename.replace(" ","_"))
Then you'll have a numerical ID that corresponds to your list for each file.
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.