Skip to main content
 首页 » 编程设计

python之如何在 python 中将目录结果转换为 csv 或 json

2024年12月31日14leader

我想编写一个 python 解析器来将 dir 结果转换为 csv 或 json。

例如,下面是dir/a/s/od/ta的结果

磁碟區 C 中的磁碟沒有標籤。 
 磁碟區序號:  123-1234 
 
 C:\ 的目錄 
 
2009/07/14  上午 11:20    <DIR>          PerfLogs 
2009/07/14  下午 01:08    <JUNCTION>     Documents and Settings [C:\Users] 
2018/03/14  下午 04:09    12,796,198,912 hiberfil.sys 
2018/03/14  下午 04:09    17,061,601,280 pagefile.sys 
2018/03/14  下午 04:16    <DIR>          Recovery 
2018/03/14  下午 04:17    <DIR>          Users 
2018/03/14  下午 04:17    <DIR>          $Recycle.Bin 
2018/03/14  下午 04:42    <DIR>          Intel 
2018/03/14  下午 05:46    <DIR>          Python27 
2018/03/22  下午 01:19                40 87E27E492B63 
2018/03/31  上午 11:08    <DIR>          py36 
2018/05/04  下午 06:12    <DIR>          ProgramData 
2018/05/04  下午 06:12    <DIR>          Program Files (x86) 
2018/05/04  下午 06:15    <DIR>          Windows 
2018/05/07  上午 10:17    <DIR>          System Volume Information 
2018/05/07  上午 10:19    <DIR>          Config.Msi 
2018/05/08  上午 10:39    <DIR>          Program Files 
               3 個檔案  29,857,800,232 位元組 

我希望它可以像下面这样

============================================================ 
|**name      |path  |lastaccess             |type**       | 
|PerfLogs    |C:\   |2009/07/14 上午 11:20  |<DIR>         | 
|hiberfil.sys|C:\   |2018/03/14  下午 04:09 |12,796,198,912| 
|pagefile.sys|C:\   |2018/03/14  下午 04:09 |17,061,601,280| 
|Recovery    |C:\   |2018/03/14  下午 04:16 |<DIR>         | 
|Users       |C:\   |2018/03/14  下午 04:17 |<DIR>         | 
|$Recycle.Bin|C:\    |2018/03/14  下午 04:17 |<DIR>         | 
|Intel       |C:\   |2018/03/14  下午 04:42 |<DIR>         | 
|Python27    |C:\   |2018/03/14  下午 05:46 |<DIR>         | 
|87E27E492B63|C:\   |2018/03/22  下午 01:19 |40            | 
|py36        |C:\   |2018/03/31  上午 11:08 |<DIR>         | 
|ProgramData |C:\   |2018/05/04  下午 06:12 |<DIR>         | 
|Windows     |C:\   |2018/05/04  下午 06:15 |<DIR>         | 
|Config.Msi  |C:\   |2018/05/07  上午 10:19 |<DIR>         | 
|ProgramFiles|C:\   |2018/05/08  上午 10:39 |<DIR>         | 
=========================================================== 

您知道我可以使用的任何 Python 库吗? 或者,如果没有图书馆可以使用,你会给我一些建议吗? 非常感谢。

请您参考如下方法:

您绝对可以使用 Pandas Library 来创建 CSV 文件。

import pandas as pd 

然后将您的数据框或列和行存储在变量 Ex 中。 df.

df.to_csv(file_name, index = False, sep=',') 

在这里,您的值将由逗号 (,) 分隔。您也可以使用 "|" 作为分隔符。