python - 为什么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'
我挠了挠头,但无法弄清楚问题。请帮我找出我的错误
谢谢,
解决方案
尽管您定义path
为'/tmp/'
,但实际上并没有在任何地方使用该值,因为这里:
if __name__ == '__main__':
newest_file = newest_file()
你什么都不传递给newest_file()
,这意味着它默认.
为你的默认 kwarg 指定的,它是并且应该是执行的当前目录。
当你尝试:
def newest_file(path):
那失败了,因为再一次,你没有向 传递任何东西newest_file()
,现在它是一个位置 arg 而不是 kwarg,它是必需的。
推荐阅读
- django - “视图 page.views.register_view 没有返回 HttpResponse 对象。它返回了 None 。” 使用自定义注册表单时出错
- mysql - MySQL:使用多个 if 语句触发
- javascript - 使用 React 的 setInterval 动画只发生一次
- actions-on-google - Actions on Google,Actions SDK - 我可以在我的 webhook 响应中使用类型覆盖来创建和更改自由文本类型吗?
- c# - SFTP使用c sharp将列表插入sql数据库表?
- ios - React Native:无法在 AppCenter 中签署 Ad-hoc iOS OneSignal 扩展
- sas - SAS按组识别单品未按预期工作
- python - 展平嵌套的json并在python中获取键和嵌套键
- android - 带有 Realm 数据库的 Dager Hilt
- python - Pymysql在查询中使用变量和列表