【发布时间】:2019-09-13 09:32:38
【问题描述】:
编辑:我的道歉:我发现了问题,我正在使用 Rstudio 运行代码,这搞砸了一些东西,我只是从控制台尝试它,它工作正常
我知道,我在做一些愚蠢的事情,但我不知道我做错了什么,我构建了这个脚本来读取一个 zip 文件,进行一些转换并编写一个最终的 csv,但由于某种原因,只有最后一个文件被写入 该脚本是完全可重现的,如果您想尝试调试它,源文件位于下面的链接中。
files = os.listdir(os.curdir)
files = [i for i in files if i.endswith('.zip')]
print(files)
for x in files:
path_file = os.path.join(curDir ,x)
print(path_file)
source = pd.read_csv(path_file,
skiprows=1,
usecols=["DISPATCH","1" ,"SETTLEMENTDATE", "RUNNO","INTERVENTION","CASESUBTYPE","SOLUTIONSTATUS","NONPHYSICALLOSSES"],
dtype=str)
source.rename(columns={'1': 'version'}, inplace=True)
source.query('version=="2"')
################ Extract UNIT, SETTLEMENTDATE,DUID,INITIALMW AND EXPORT TO CSV
df_unit=source
df_unit=df_unit.query('DISPATCH=="DUNIT" or DISPATCH=="TUNIT"')
#Make first row a header
df_unit.columns = df_unit.iloc[0]
df_unit = df_unit[1:]
#create a conditional column
df_unit.loc[df_unit['DUNIT'] == 'TUNIT', 'INITIALMW1'] = df_unit['INTERVENTION']
df_unit.loc[df_unit['DUNIT'] == 'DUNIT', 'INITIALMW1'] = df_unit['INITIALMW']
df_unit.drop(columns=['RUNNO','2','INTERVENTION','INITIALMW','DISPATCHMODE'],inplace=True)
df_unit.rename(columns={'INITIALMW1': 'INITIALMW','DUNIT': 'UNIT'}, inplace=True)
df_unit=df_unit.query('SETTLEMENTDATE!="SETTLEMENTDATE" and INITIALMW !="0"')
df_unit["INITIALMW"] = pd.to_numeric(df_unit["INITIALMW"])
df_unit['SETTLEMENTDATE']=pd.to_datetime(df_unit['SETTLEMENTDATE'])
df_unit.head()
df_unit.to_csv(x.rsplit('.', 1)[0] + '.csv',float_format="%.4f",
index=False,date_format='%Y-%m-%dT%H:%M:%S.%fZ',compression='gzip')
print(path_file)
编辑:我添加了列表文件:
['PUBLIC_DAILY_201906040000_20190605040502.zip', 'PUBLIC_DAILY_201906050000_20190606040501.zip', 'PUBLIC_DAILY_201907140000_20190715040502.zip']
文件从here下载。
【问题讨论】:
-
你能粘贴
files吗?它看起来怎么样? -
@vbrises 请查看编辑
-
@Mim:我认识到,在您对
to_csv的调用中,您没有添加路径。该文件是否有可能实际写入另一个目录?你检查过os.getcwd()返回的目录了吗? -
如果你想将文件写入与输入文件相同的目录,你可以在
to_csv行中将x替换为path_file。 -
@jottbe,结果相同