Reputation: 79
Here is my code:
import os
import time
initial_date = '22.01.2015 02:00:00'
initial = time.mktime(time.strptime(initial_date, "%d.%m.%Y %H:%M:%S"))
final_date = '15.04.2015 03:45:00'
final = time.mktime(time.strptime(final_date, "%d.%m.%Y %H:%M:%S"))
path = 'Transfer\Praktikanten\2017-05-Sharon\M02_Modelldaten\Sofia_HW_032015_12\01.01.2015-31.12.2015_2014\22.02.2015-15.04.2015_201410XX'
directory = os.path.join("x:\\","path")
for root,dirs,files in os.walk(directory):
for files in directory:
if file.endswith(".csv"):
f_in=open(file, 'r').readlines()
Datum_Uhrzeit= []
Wasserstand= []
f_out = open('NEW_file','w')
f_out.write(f_in[0])
for i in range(1, len(f_in)):
Datum_Uhrzeit= f_in[i].split(';',)[0]
Wasserstand = f_in[i].split(';')[1]
Datum_Uhrzeit= time.mktime(time.strptime(Datum_Uhrzeit, "%d.%m.%Y %H:%M:%S"))
if initial <= Datum_Uhrzeit <= final:
f_out.write(f_in[i])
f_out.close()
I am trying to extract the given date time from all CSV files in the mentioned folder and write these data in a new_file.
Sample CSV file: CSV file headers and data
The code returns no errors but it doesn't generate the new files.
Upvotes: 2
Views: 175
Reputation: 79
So I managed to solve it. Here is the code if anyone needs in the future:
import os
import time
initial_date = '22.02.2015 02:00:00'
initial = time.mktime(time.strptime(initial_date, "%d.%m.%Y %H:%M:%S"))
final_date = '15.04.2015 03:45:00'
final = time.mktime(time.strptime(final_date, "%d.%m.%Y %H:%M:%S"))
path = 'x:/Transfer/Praktikanten/2017-05-Sharon/M02_Modelldaten/Sofia_HW_032015_12/01.01.2015-31.12.2015_2014/22.02.2015-15.04.2015_201410XX/'
for root,dirs,files in os.walk(path):
for file in files:
if file.endswith(".csv"):
f_out = open('NEW_' + file,'w')
f_in=open(file, 'r').readlines()
f_out.write(f_in[0])
for i in range(1, len(f_in)):
Datum_Uhrzeit= f_in[i].split(';',)[0]
Datum_Uhrzeit = time.mktime(time.strptime(Datum_Uhrzeit, "%d.%m.%Y %H:%M:%S"))
if initial <= Datum_Uhrzeit <= final:
f_out.write(f_in[i])
f_out.close()
Upvotes: 2