如果值不在使用python的数据中,则跳过文件



使用我当前的代码,如果csv文件在我要查找的实际数据中不包含值,我将尝试跳过该文件。

基本上如果它具有";PROD_NAME";作为一列,它会查找该字符串并将其替换为该语句中的第二个字符串,但文件夹中的第一个文件没有该列名,因此脚本失败。我研究过跳过的方法,但只看到了基于文件名本身而不是文件中没有正确信息的数据的跳过方法。如有任何帮助,我们将不胜感激。谢谢

def worker(files):
filenames = glob.glob(dest_dir + '\*.csv')
for filename in filenames:

my_file = Path(os.path.join(dest_dir, filename))

#read header
with open(filename) as f:
read_data = f.read()
header = read_data[:read_data.find('!1')]
idx = header.find('n')

# read data
df1 = pd.read_csv(filename, skiprows=1, encoding='ISO-8859-1', nrows=1) # read column header only - to get the list of columns
dtypes = {}
for col in df1.columns:# make all columns text, to avoid formatting errors
dtypes[col] = 'str'
df1 = pd.read_csv(filename, dtype=dtypes, skiprows=1, encoding='ISO-8859-1', quotechar="'", delimiter='t')


df1.loc[df1['PROD_NAME'].str.contains('NA_NRF'), 'PROD_NAME'] = 'FA_GUAR'
file_count += 1 # count the fil

worker(files)

您能在转换之前添加一个if语句吗

if 'PROD_NAME' in df1.columns:            
df1.loc[df1['PROD_NAME'].str.contains('NA_NRF'), 'PROD_NAME'] = 'FA_GUAR'

file_count += 1 # count the fil

最新更新