根据python中的条件从文件夹中读取CSV文件
我想根据条件从文件夹中读取CSV文件。我只想阅读文件名中包含“ 1441”的CSV文件。我使用了FNMatch,但它不起作用。谁能帮忙?
path_to_parent = r"C:\Users\Desktop\books/chapter_1"
for csv_file in os.listdir(path_to_parent):
if fnmatch.fnmatch(csv_file,'1441'):
my_file = pd.read_csv(path_to_parent+csv_file)
else:
print('error')
I want to read csv files from a folder based on condition. I just want to read csv files that include “1441” in the filename. I used fnmatch, but it doesn’t work. Can anyone help?
path_to_parent = r"C:\Users\Desktop\books/chapter_1"
for csv_file in os.listdir(path_to_parent):
if fnmatch.fnmatch(csv_file,'1441'):
my_file = pd.read_csv(path_to_parent+csv_file)
else:
print('error')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要围绕
1441
的通配符来匹配文件名的其余部分。否则,它正在寻找确切的文件名1441
。另外,您不会在
path_to_parent
和csv_file
之间添加目录分离器。最好将os.path.join()
用于便携性。我还建议您改用
glob.glob()
。它将为您提供通配符匹配,并且会返回完整的路径,因此您不必每次通过循环进行连接。You need wildcards around
1441
to match the rest of the filename. Otherwise it's looking for the exact filename1441
.Also, you're not adding the directory separator between
path_to_parent
andcsv_file
when you concatenate them. It's best to useos.path.join()
for portability.I also recommend using
glob.glob()
instead. It will do the wildcard matching for you, and it will return full paths so you don't have to concatenate each time through the loop.您可以尝试使用不同的方法对您的if语句进行稍作修改。
You could try different approach with slight modification to your if statement.