I wrote a program that merges several text files together, and from there, I am trying to add dates to the first column using a for loop since there are several different dates. Using these loops though, the program doesn’t seem to iterate properly.
The supporting text files have a list of times without dates; however, each text file is associated with a different date. I am merging all of the text files together into one text file for easier use, though to make it useful, I am trying to add the dates to the times, which appears in the first column of the text file.
Here’s what the code looks like:
import glob
from datetime import *
mon = [6, 7]
dayrange1 = [24, 25, 26, 27, 28, 29, 30]
dayrange2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
m = 0
d1 = 0
d2 = 0
newline = []
fout = open("C:\\Users\\jessica.macleod\\Desktop\\SurmontArray1.txt", "a")
for filename in glob.glob("C:\\Users\\jessica.macleod\\Desktop\\Surmont Noise Files\\s1-424surmontnoise2012*.txt"):
f = open(filename)
f.next()
f.next()
d1 = 0
d2 = 0
for months in mon:
if m == 0:
for days in dayrange1:
for line in f:
line += str(date(2012, mon[m], dayrange1[d1])) + " "
fout.write(line)
d1 = d1 + 1
m = m + 1
if m == 1:
for days in dayrange2:
for line in f:
line += str(date(2012, mon[m], dayrange2[d2])) + " "
fout.write(line)
d2 = d2 + 1
f.close()
fout.close()
dayrange1is not iterated over in the second loop offor months in monbecause you have setmto1. It is skipped because it is guarded by the conditionalif m == 0:. This means that only the very first matched filename in your glob will have the results of iterating overdayrange1. You’ll need to resetmto0inside of one of your loops.Also, you iterate over
daysindaterange1. During the first iteration of that loop you iterate over the entire contents off. That means on the second iteration overdaterange1the file is used up.Also, you don’t use
daysinside of your loop.