简体   繁体   English

使用.to_csv() 根据另一个文件保存文件名和扩展名

[英]Save file name and extension based on another file with .to_csv()

I have an input file name file_a.xml我有一个输入文件名file_a.xml

I already created a function to parse out the xml and save it as a df.我已经创建了一个 function 来解析 xml 并将其保存为 df。 Then I used df.to_csv to save the output file name file_a.csv然后我用df.to_csv保存了output文件名file_a.csv

Is there a way to do this automatically with default filename and extension?有没有办法使用默认文件名和扩展名自动执行此操作? I need to iterate over a folder with lots of.xml files, so I like to the output filename & extension it based on the input xml file.我需要遍历一个包含大量.xml 文件的文件夹,所以我喜欢 output 文件名和基于输入 xml 文件的扩展名。

xml_file = open ('file/path/dir/file_a.xml','r').read()

def XML_to_CSV(xml_file):
    ...code to parse out xml...
    return df 

csv_data = df.to_csv('file/path/dir/file_a.csv',index = False)

Try something like this:尝试这样的事情:

import os
import pandas as pd
from pathlib import Path

for file in os.listdir("your dir"):
    if file.endswith(".xml"):
        ...make the xml turn df.
        df.to_csv(Path(file).stem + '.csv', index=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM