beeedy
beeedy

Reputation: 29

python write to file does not write

I have found similar questions, and tried the solutions proposed within, and none seem to solve my problem. What I am attempting to do is in essence copy the data from one file to another, and even though it does not error our and I have verified the 'line' variable is a string and contains the correct data, it simply does not write to the file. I am currently using python 2.7.

I have attempted to add .flush() as some other solutions have suggested with no success. I have verified that if I write a static string before the first for loop, it does in fact write to the file. My suspicion is it has something to do with having both files open and iterating through one of them, but I am unsure on the validity of this.

with open("data/data.csv", 'w+') as data_file, open("data/raw/" + data_point + ".csv", 'r') as raw_file:
    for line in raw_file:
        line = line.split(',')
        temp_date = datetime(int(line[0]), int(line[1]), int(line[2]))
        if newest_date == datetime(1,1,1):
            newest_date = temp_date
        if temp_date < oldest_date:
            oldest_date = temp_date
        sorted_raw = [[float(line[4]), float(line[5])]] + sorted_raw

    raw_file.seek(0) # reset read pointer 
    for line in raw_file:
        data_file.write(line)

EDIT: I now realize my idiocies. I had a second uncompleted function that was basicly a modified copy paste of this, but with no writes. the "w+" method of opening the file cleared it every time and since this second function was always called right after this block of code finished I was never able to catch the written file. I apologize for the noise

Upvotes: 0

Views: 117

Answers (1)

Soviut
Soviut

Reputation: 91515

You could just write to the data file in your first loop.

with open("data/data.csv", 'w+') as data_file, open("data/raw/" + data_point + ".csv", 'r') as raw_file:
    for line in raw_file:
        line = line.split(',')
        temp_date = datetime(int(line[0]), int(line[1]), int(line[2]))
        if newest_date == datetime(1,1,1):
            newest_date = temp_date
        if temp_date < oldest_date:
            oldest_date = temp_date
        sorted_raw = [[float(line[4]), float(line[5])]] + sorted_raw

        data_file.write(line)

Upvotes: 1

Related Questions