Search code examples
pythonenumerate

Is there a better way of doing this?


Is there another way of checking if something is first?

I've been using for i,f in enumerate(read_files) where I enumerate a list of files, and use an if statement to check if i==0. I'm curious is there is a different (better, faster, less typed) way to do this?

read_files = glob.glob("post_stats_*.tsv") 
with open("result.tsv", "w") as outfile: 
    for i,f in enumerate(read_files): 
        with open(f, "r") as infile: 
            metric_name = (f.strip(".tsv").split("_")[2]) 
            if i == 0: 
                outfile.write(metric_name.upper() + "\n" + infile.read()) 
            else: 
                outfile.write("\n" + metric_name.upper() + "\n" + infile.read()) 

Solution

  • Since it seems the only use of the if is to avoid a blank line at the start of the output file, how about putting the blank line after the file's contents? That will lead to a blank line at the end of the file where it's unlikely to hurt:

    read_files = glob.glob("post_stats_*.tsv") 
    with open("result.tsv", "w") as outfile: 
        for f in read_files: 
            with open(f, "r") as infile: 
                metric_name = (f.strip(".tsv").split("_")[2]) 
                outfile.write(metric_name.upper() + "\n" + infile.read() + "\n")