我想使用file=glob.glob...
函数读取文件夹中的文件名。
并在'file_last_mod_t'
列中添加最后一次修改文件时间。
我的部分代码:
df=pd.DataFrame(columns=['filename','file_last_mod_t','else'])
df.set_index('filename')
for file in glob.glob('folder_path'): #inside this folder is file.txt
file_name=os.path.basename('folder_path')
df.loc[file_name]= os.path.getmtime(file)
这给了我
df:
filename,file_last_mod_t,else
file.txt,123456,123456 #123456 its time result example
我只想将此最后一次修改时间添加到file_last_mod_t
列,而不是全部添加。
我想收到:
df:
filename,file_last_mod_t,else
file.txt,123456,
多谢建议
修改代码后:
df=pd.read_csv('C:/df.csv')
filename_list= pd.Series(result_from_other_definition)# it looks same as in #filename column
df['filename']=filename_list # so now i have dataframe with 3 columns and firs column have files list
df.set_index('filename')
for file in glob.glob('folder_path'):#inside this folder is file.txt
df['file_last_mod_t']=df['filename'].apply(lambda x: (os.path.getmtime(x)) #the way how getmtime is present is now no matter, could be #float numbers
df.to_csv('C:/df.csv')
#打印样本: 首次运行:
df['filename']=filename_list
print (df)
,'filename','file_last_mod_t','else'
0,file1.txt,NaN,NaN
1,file2.txt,NaN,NaN
上面的代码在df为空(仅包含标头)时首次运行后可以正常工作。
在下一次运行后,当我运行代码并且df.csv
有一些内容i am changing manually value of timestamp in file
时,我收到一条错误消息:TypeError: stat: path should be string, bytes, os.PathLike or integer,not float
该代码应替换具有良好时间戳的手动修改的单元格。我认为它与apply
相关
我也不知道为什么索引出现在dp
**已解决**
答案 0 :(得分:1)
请参见以下代码注释:
import os
import pandas as pd
import datetime as dt
import glob
# this is the function to get file time as string
def getmtime(x):
x= dt.datetime.fromtimestamp(os.path.getmtime(x)).strftime("%Y-%m-%d %H:%M:%d")
return x
df=pd.DataFrame(columns=['filename','file_last_mod_t','else'])
df.set_index('filename')
# I set filename list to df['filename']
df['filename'] = pd.Series([file for file in glob.glob('*')])
# I applied a time modified file to df['file_last_mod_t'] by getmtime function
df['file_last_mod_t'] = df['filename'].apply(lambda x: getmtime(x))
print (df)
结果是
filename file_last_mod_t else
0 dataframe 2019-05-04 18:43:04 NaN
1 fer2013.csv 2018-05-26 12:18:26 NaN
2 file.txt 2019-05-04 18:49:04 NaN
3 file2.txt 2019-05-04 18:51:04 NaN
4 Untitled.ipynb 2019-05-04 17:41:04 NaN
5 Untitled1.ipynb 2019-05-04 20:51:04 NaN
对于更新后的问题,我从df.csv
开始,其数据如下:
filename,file_last_mod_t,else
file1.txt,,
而且,我想您想添加新文件。因此,我编写了如下代码:
import os
import pandas as pd
df=pd.read_csv('df.csv')
df_adding=pd.DataFrame(columns=['filename','file_last_mod_t','else'])
df_adding['filename'] = pd.Series(['file2.txt'])
df = df.append(df_adding)
df = df.drop_duplicates('filename')
df['file_last_mod_t']=df['filename'].apply(lambda x: (os.path.getmtime(x))) #the way how getmtime is present is now no matter, could be #float numbers
df.to_csv('df.csv', index=False)
我为新文件创建了df_adding
数据帧,并将其附加到读取df.csv
的df上。
最后,我们可以应用getmtime
并将其保存到df.csv
。