首页 > 解决方案 > 为什么python程序无法访问远程路径?

问题描述

我编写了几个函数来获取最新文件。该代码似乎工作正常,只是它没有列出目标路径中的文件,而是列出了 python 程序所在位置的文件。下面是代码:

import os
import platform

path = '/tmp/'

def newest_file(path='.'):
    files = os.listdir(path)
    paths = [os.path.join(path, basename) for basename in files]
    if platform.system() == 'Windows':
        return max(paths, key=os.path.getctime)
    else:
        return max(paths, key=os.path.getmtime)

def stamp(newest_file):
    file_stamp = os.path.getmtime(newest_file)
    return file_stamp, newest_file

def file_compare(file_stamp, file_name):
    try:
        with open(f'{path}stamp.txt') as f:
            old_stamp = float(f.read())
        if old_stamp == file_stamp:
            print(f'No change: {file_name} --> {file_stamp}')
        else:
            print(f'New file: {file_name} --> {file_stamp}')
            logger.info(f'{file_name} --> {file_stamp}')
            with open(f'{path}stamp.txt', 'w') as f:
                f.write(str(file_stamp))
    except OSError:
        with open(f'{path}stamp.txt', 'w') as f:
            f.write(str(file_stamp))

if __name__ == '__main__':
    newest_file = newest_file()
    file_stamp = stamp(newest_file)[0]
    file_name = os.path.basename(stamp(newest_file)[1])
    file_compare(file_stamp, file_name)

因此,它不是列出来自“/tmp”的文件,而是列出来自“/opt”的文件,它是我的python代码所在的位置。如果我使用

`path = glob.iglob('/tmp/*.txt')` 

并使用

def newest_file(path):

并从程序中删除变量“文件”和“路径”,我得到以下错误:

Traceback (most recent call last):
  File "new_x20.py", line 45, in <module>
    newest_file = newest_file()
TypeError: newest_file() missing 1 required positional argument: 'path'

我挠了挠头,但无法弄清楚问题。请帮我找出我的错误

谢谢,

标签: pythonpython-3.6

解决方案


尽管您定义path'/tmp/',但实际上并没有在任何地方使用该值,因为这里:

if __name__ == '__main__':
    newest_file = newest_file()

你什么都不传递给newest_file(),这意味着它默认.为你的默认 kwarg 指定的,它是并且应该是执行的当前目录。

当你尝试:

def newest_file(path):

那失败了,因为再一次,你没有向 传递任何东西newest_file(),现在它是一个位置 arg 而不是 kwarg,它是必需的。


推荐阅读