【问题标题】:Resolve Unconverted Data Remains: Error without replace other file contents解决未转换的数据残留:错误而不替换其他文件内容
【发布时间】:2021-08-14 04:41:03
【问题描述】:

我目前正在编写一个对日期进行排序的脚本。我有一个名为sample.txt 的输入文件和一个名为sample2.txt 的输出文件。最后,输入文件的内容应该被排序并写入输出文件。但是在运行我的脚本时,我遇到了以下错误:Unconverted Data Remains: Dentist。这是因为strptime 无法转换Dentist。所以我的问题是:如何在不删除 Dentist 一词或其他无日期内容的情况下修复此错误?

这是完整的错误信息:

Traceback (most recent call last):
  File "test3.py", line 156, in <module>
    main_user_input.user_input()
  File "test3.py", line 144, in user_input
    list_next_appointments.list_next_appointments_main()
  File "test3.py", line 96, in list_next_appointments_main
    bands = sorted(bands, key=lambda date: datetime.strptime(date, "%d.%m.%Y"))
  File "test3.py", line 96, in <lambda>
    bands = sorted(bands, key=lambda date: datetime.strptime(date, "%d.%m.%Y"))
  File "/home/supre/anaconda3/lib/python3.8/_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/home/supre/anaconda3/lib/python3.8/_strptime.py", line 352, in _strptime
    raise ValueError("unconverted data remains: %s" %
ValueError: unconverted data remains:  Dentist

这是我输入文件的内容:

23.08.2021 Dentist 
13.08.2031 Surgery 
13.01.2022 Family 

这是我的代码:

with open('sample.txt', 'r') as file1, open('sample2.txt','w+') as file2:
    bands = (line.strip() for line in file1)
    bands = sorted(bands, key=lambda date: datetime.strptime(date, "%d.%m.%Y"))
    file2.write(' \n'.join(bands))

提前感谢您的每一个帮助和建议:)

【问题讨论】:

    标签: python python-3.x sorting datetime strptime


    【解决方案1】:

    如果您的输入文件始终按照您显示的方式进行格式化,即 2 列,避免错误的最简单方法是使用 .strptime 仅转换日期列。换句话说,将行拆分为日期文本并休息:

    
    with open('sample.txt', 'r') as file1, open('sample2.txt','w+') as file2:
        bands = (line.strip() for line in file1)
        bands = sorted(bands, key=lambda line: datetime.strptime(line.split()[0], "%d.%m.%Y"))
        file2.write(' \n'.join(bands))
    

    【讨论】:

    • 非常感谢您的快速响应和帮助:) 这为我解决了问题:)
    猜你喜欢
    • 2017-10-07
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 2017-10-04
    相关资源
    最近更新 更多