【问题标题】:Concatenate Error while adding date format to existing file path in python将日期格式添加到python中的现有文件路径时出现连接错误
【发布时间】:2020-06-28 06:56:24
【问题描述】:

你好 stackflowers,我是新手,我需要帮助

我最近在 python 中学习 pandas 库并尝试自动化输出文件,我成功了。但是当我想到将日期添加到输出路径时,我面临的错误是“只能将列表(而不是“str”)连接到列表中”

谁能帮我解决这个问题...

#saving in a path

timestamp = datetime.datetime.now()
t = timestamp.year, timestamp.month, timestamp.day

path = r'C:\Users\Revanth\Desktop\pandas_tutorials\New_Idle_Artist_List.xlsx'

split_filename = path.split(".")
exportpath = os.rename(path, split_filename[:-1]+'-'+join(t))

writer = pd.ExcelWriter(exportpath,engine='xlsxwriter',datetime_format='mmm d yyyy')




**Error displayed** : runfile('C:/Users/Revanth/.spyder-py3/Idle_artist_appliction.py', wdir='C:/Users/Revanth/.spyder-py3') Traceback (most recent call last):

  File "C:\Users\Revanth\.spyder-py3\Idle_artist_appliction.py", line 71, in <module>
    exportpath = os.rename(path, [split_filename[:-1]+'-'+join(t)])

TypeError: can only concatenate list (not "str") to list

【问题讨论】:

  • 查看标准库中的 pathlib 模块,以便在 Python 中正确处理路径和文件名

标签: python python-3.x pandas datetime


【解决方案1】:

这是我的评论示例,您如何使用 pathlib 模块中的 Path 类构建导出路径。乍一看可能看起来很复杂,但从长远来看会得到回报,因为一旦你习惯了它就非常方便。

from datetime import datetime
from pathlib import Path

path = Path(r'C:\Users\Revanth\Desktop\pandas_tutorials\New_Idle_Artist_List.xlsx')

datestring = datetime.now().strftime('%Y-%m-%d')
# e.g. '2020-06-28'

exportpath = path.parent/f'{path.stem}-{datestring}{path.suffix}'
# e.g. WindowsPath('C:/Users/Revanth/Desktop/pandas_tutorials/New_Idle_Artist_List-2020-06-28.xlsx')
  • 首先,我们从路径字符串创建一个 Path 对象(原始字符串模式,因为我们有单个反斜杠)
  • 使用strftime 构造今天的年-月-日字符串
  • 制作导出路径。 path.parent 是除了文件名之外的所有内容。然后我们可以使用/ 将它与我们使用f-string 构造的新文件名结合起来。 path.stem 是不带扩展名的文件名; path.suffix 只是扩展名。

参考:pathlibf-strings

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多