【问题标题】:Search if filename with matching 4 digits exists in a directory搜索目录中是否存在匹配 4 位数字的文件名
【发布时间】:2021-12-10 21:05:17
【问题描述】:

我正在检查路径中是否存在文件名 - 'Dev Finance GRM CONS ASPAC_Sales_3069_WI2_2020_GrsSalesAdj_Manual Upload Planning_1000records.csv'

我在同一路径中生成多个名称相似的文件,但在上述情况下是唯一的 pin ('3069')。此“3069”存储在唯一变量“upload_pin”中

upload_pin = 3069(我想搜索包含此 upload_pin 的 .csv 文件是否存在于我的路径中)

试过这个:

path = r"\\OPCITSNAPADCON2.jnj.com\tm1\cons\grm_aspac\user_in\Manual Upload Current Plan\Archive"
csv_files = glob.glob(os.path(path + '/*.csv'))
for filename in csv_files:
    if upload_pin in filename:
               print(filename)

【问题讨论】:

  • 可能你所缺少的只是将upload_pin 变成一个字符串,这样你就可以检查它是否在文件名中。如果它写成upload_pin = 3069,那么它将是一个int,而不是一个字符串。正如@Jeremy 建议的那样,if str(upload_pin) in filename 可能就足够了。

标签: python pandas glob


【解决方案1】:

试试

# get file names of all csv files in the directory
os.chdir('...')
all_csv_files = glob.glob("*.csv")

# provide your pin
upload_pin = 3069

# for each one of your files
# if the file name contains the target pin, print the file name
for file in all_csv_files:
    if (str(upload_pin) in file):
        print(file)

【讨论】:

  • 感谢@Jeremy...但我无法使用 os.chdir('...') 更改目录,因为我的程序继续并在前一个目录中搜索文件。这就是为什么我尝试使用 glob.glob(os.path(path + '/*.csv'))....使用 str(upload_pin)
  • .....给出错误:csv_files = glob.glob(os.path(path + '/*.csv')) TypeError: 'module' object is not callable
【解决方案2】:

这对我有用

import os

upload_pin = 3069
for filename in os.listdir():
    if filename.endswith(".csv") and filename.find(str(upload_pin))>=0:
        print(filename)
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多