这是我的代码:
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()
我正在尝试从上述文件夹中的所有CSV文件中提取给定的日期时间,并将这些数据写入new_file。
示例CSV文件: CSV file headers and data
代码不返回任何错误,但它不会生成新文件。
答案 0 :(得分:2)
所以我设法解决了这个问题。以下是任何人未来需要的代码:
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()
答案 1 :(得分:1)