解析未转换的数据:错误,不替换其他文件内容

2024-03-29 08:45:22 发布

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

我目前正在写一个对日期进行排序的脚本。我有一个名为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))

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


Tags: 文件lambdainpytxt内容datetimedate
1条回答
网友
1楼 · 发布于 2024-03-29 08:45:22

如果您的输入文件总是按照您显示的方式格式化,即在两列中格式化,那么避免错误的最简单方法是使用.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))

相关问题 更多 >