如何使用 pathlib.Path().glob() 读入文件并将具有相同文件名的文件输出到另一个子文件夹
How to read in a file and output the file with the same file name into another subfolder using pathlib.Path().glob()
如何使用pathlib.Path().glob()
读入文件并将具有相同文件名的文件输出到另一个子文件夹?
我的目录如下所示:
New Folder 1
-> p1_a.csv
-> p1_b.csv
-> New Folder 2
代码:
from pathlib import Path
import pandas as pd
file_path = r'C:\Users\HP\Desktop\New Folder 1'
for fle in Path(file_path).glob('p1_*.csv'):
df = pd.read_csv(fle)
# do something with df
df.to_excel(file_path + r'\New Folder 2' + 'p1_*.csv' + '_new.csv')
我不确定的代码是'p1_*.csv'
。
代码为运行后,我的目录应该是这样的:
New Folder 1
-> p1_a.csv
-> p1_b.csv
-> New Folder 2
-> -> p1_a.csv_new.csv
-> -> p1_b.csv_new.csv
我需要在 'p1_*.csv'
位中包含什么,以便复制到新文件夹 2 中的新文件具有与原始文件相同的部分文件名?
非常感谢。
试试这个:
import os
import pandas as pd
from pathlib import Path
source_dir = r'C:/Users/HP/Desktop/New Folder 1'
for path in Path(source_dir).glob('p1_*.csv'):
df = pd.read_csv(path)
# TODO: do something with df
filename = os.path.basename(path) #--> gets the file name
dest_path = os.path.join(source_dir, "New Folder 2", f"{filename}_new.csv")
df.to_csv(dest_path)
现在您的目录结构将如下所示:
New Folder 1
├── New Folder 2
│ ├── p1_a.csv_new.csv
│ └── p1_b.csv_new.csv
├── p1_a.csv
└── p1_b.csv
与 Shubham 的基本相同,没有调用 os 模块:
for fle in Path(file_path).glob('p1_*.csv'):
df = pd.read_csv(fle)
# do something with df
new_location = Path(file_path).parent.joinpath('New Folder 2', f'{fle}_new.csv')
df.to_excel(new_location)
如何使用pathlib.Path().glob()
读入文件并将具有相同文件名的文件输出到另一个子文件夹?
我的目录如下所示:
New Folder 1
-> p1_a.csv
-> p1_b.csv
-> New Folder 2
代码:
from pathlib import Path
import pandas as pd
file_path = r'C:\Users\HP\Desktop\New Folder 1'
for fle in Path(file_path).glob('p1_*.csv'):
df = pd.read_csv(fle)
# do something with df
df.to_excel(file_path + r'\New Folder 2' + 'p1_*.csv' + '_new.csv')
我不确定的代码是'p1_*.csv'
。
代码为运行后,我的目录应该是这样的:
New Folder 1
-> p1_a.csv
-> p1_b.csv
-> New Folder 2
-> -> p1_a.csv_new.csv
-> -> p1_b.csv_new.csv
我需要在 'p1_*.csv'
位中包含什么,以便复制到新文件夹 2 中的新文件具有与原始文件相同的部分文件名?
非常感谢。
试试这个:
import os
import pandas as pd
from pathlib import Path
source_dir = r'C:/Users/HP/Desktop/New Folder 1'
for path in Path(source_dir).glob('p1_*.csv'):
df = pd.read_csv(path)
# TODO: do something with df
filename = os.path.basename(path) #--> gets the file name
dest_path = os.path.join(source_dir, "New Folder 2", f"{filename}_new.csv")
df.to_csv(dest_path)
现在您的目录结构将如下所示:
New Folder 1
├── New Folder 2
│ ├── p1_a.csv_new.csv
│ └── p1_b.csv_new.csv
├── p1_a.csv
└── p1_b.csv
与 Shubham 的基本相同,没有调用 os 模块:
for fle in Path(file_path).glob('p1_*.csv'):
df = pd.read_csv(fle)
# do something with df
new_location = Path(file_path).parent.joinpath('New Folder 2', f'{fle}_new.csv')
df.to_excel(new_location)