我在尝试重命名大量子文件夹中的 Json 文件时遇到了困难。我想要做的是用计数变量替换 json 文件。因为,每个 .json 文件在其各自的文件夹中都以 messages_1.json 结尾。
这里的 Person_1、Person_2、Person_3、......、Person_n 是收件箱文件夹内的各个子文件夹
示例文件结构
- C:/abc/def/ghi/klmn/opq/rst/uvw/xyz/messages/Inbox:
- Person_1
- message_1.json
- Person_2
- message_1.json
- Person_3:
- message_1.json
.
.
.
.
- Person_n:
- message_1.json
此外,我想将它们保存为单个熊猫数据框,然后将其导出为 csv 文件,我可以在其中进一步处理创建的数据框。
这是我到目前为止尝试过的并且卡住了:
我试过的代码:
directory = os.path.dirname(os.path.realpath(sys.argv[0]))
for root, dirs, files in os.walk("C:/abc/def/ghi/klmn/opq/rst/uvw/xyz/messages/inbox/"):
for name in files:
if name.endswith((".json")):
folder_names = os.path.relpath(root, directory)
json_files = os.path.join(folder_names, name)
我想得到的输出
- Person_1
- message_1.json
- Person_2
- message_2.json
- Person_3:
- message_3.json
.
.
.
.
- Person_n:
- message_n.json
或
All replaced json names and then a single csv file with all json files
任何帮助将不胜感激我无法理解如何获得这个
使用pathlib
建立数据框,然后可以重命名文件。
from pathlib import Path
import pandas as pd
pth = Path("C:/abc/def/ghi/klmn/opq/rst/uvw/xyz/messages/inbox/")
data = [(f, f.parent, f.stem, f.suffix)
for f in pth.rglob('*.json')]
# load into dataframe
df = pd.DataFrame(data=data, columns=['pth', 'dname', 'fname', 'suffix'])
# create new filename
df['new_name'] = (
df['fname'].str.split('_').str[0] +
'_' +
(df.index + 1).astype(str) +
df['suffix']
)
# now rename each file
for row in df.itertuples():
row.pth.rename(Path(row.dname) / row.new_name)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句