Python 尝试重命名文件时出现错误123
我正在尝试编写一个以文件名作为输入的代码。在我的计算机上查找此文件,然后根据文件前两行的文本更改文件名Python 尝试重命名文件时出现错误123,python,windows,oserror,Python,Windows,Oserror,我正在尝试编写一个以文件名作为输入的代码。在我的计算机上查找此文件,然后根据文件前两行的文本更改文件名 import os filename = input("Enter your file name: ") def info(filename): with open(filename, 'r') as filehandle: current_line = 1 for line in filehandle: i
import os
filename = input("Enter your file name: ")
def info(filename):
with open(filename, 'r') as filehandle:
current_line = 1
for line in filehandle:
if current_line <=2:
yield(line)
current_line += 1
info = list(info(filename))
print(info)
path = r'C:\Users\marku\Desktop\INF100'
date = str(info[1])
place = str(info[0])
finalname = date + '_' + place + '.txt'
old = os.path.join(path, filename)
new = os.path.join(path, finalname)
os.rename(old, new)
请将完整的错误回溯作为您问题的一部分。这是否回答了您的问题?是的,这就是我认为问题在于文件名中有一个“\n”。在将列表中的每个元素设置为字符串后,我尝试更改此设置。但它似乎不是字符串的一部分,而是文件名的一部分。我不确定如何从新文件名中删除此项。给定filehandle:中的行的行
,行
将包含尾随的“\n”
(换行符)。您可能需要执行yield(line.strip())
来删除换行符。谢谢Justin,绝对传奇!谢谢你的帮助