Python脚本在Jupyter中工作,但不是命令行,listdi

2024-05-08 18:38:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python脚本,如果hash是可用的(检查一个csv中的hash和文件路径,然后在数据帧中添加列),那么我想将一个文件移动到一个新的位置

我在脚本中遇到了一个问题,我的路径是以浮点形式出现的,而它应该是一个字符串。在我的jupyter笔记本中,当我执行print(type(path))时,输出是<class 'str'>,但是当我在脚本中执行print(type(path))时,当我在命令行上运行它时,它返回<class 'float'>

运行完整脚本时,出现以下错误:

错误

Traceback (most recent call last):
  File "compare_hashes_to_image_hashes.py", line 82, in <module>
    for source_filename in os.listdir(path):
TypeError: listdir: path should be string, bytes, os.PathLike, integer or None, not float

为什么它在我的jupyter笔记本中工作,而不是在我的脚本中

脚本(与问题相关的部分)

#!/usr/bin/python36

import os
import shutil

# make columns into lists
users = list(master_df['USER_JID'])
avails = list(master_df['HASH_AVAILABLE'])
paths = list(df_merged['FILE_PATH'])
hashes = list(df_merged['SHA1_BASE16'])

# define source location and destination location
destination = "/opt/PhotoTips/input/"
source_img = "/opt/PhotoTips/hash_images/"

"""
Move images to appropriate user img folders
"""

# for every value in available list
for i in range(len(avails)):
    # each value in user list is a user
    user = users[i]
    # each value in path list is a path
    path = paths[i]
    # each value in hash value list is a hash
    hash_val = hashes[i]
    # build full location
    location = destination + user + '/img'
    # if hash image is available
    if 'Available' in avails[i]:
        # debug purposes
        # print(type(path)) # returns <class 'float'>
        # suggested by marklap
        # if isinstance(path, float): 
            # print(path)
            # returns nan
        for source_filename in os.listdir(path):   <---- line with the issue
            # confirm text file for match
            if source_filename.startswith(hash_val):
                # build full path
                source_file_path = os.path.join(path, source_filename)
                # copy image to appropriate user location
                shutil.copy(source_file_path, location)
    # if hash image is NOT available
    else:
        # do nothing
        pass

Tags: pathin脚本sourceforifisvalue