以下是参考代码:
import shutil
import datetime
import os.path
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
if not os.path.exists('copy_path.txt'):
root = Tk()
root.withdraw()
file_to_backup = askopenfilename(title=' ')
backup_directory = askdirectory(title=' ')
print(file_to_backup)
print(os.path.exists(file_to_backup))
if os.path.exists(file_to_backup):
if os.path.exists(backup_directory):
copy_path_file = open('copy_path.txt', 'w+')
copy_path_file.write(file_to_backup + '\n' + backup_directory)
copy_path_file.close()
if os.path.exists('copy_path.txt'):
copy_path_file = open('copy_path.txt', 'r')
paths = copy_path_file.readlines()
#paths[0] = paths[0].replace('/','\\')
print(paths[0])
print(os.path.exists(paths[0]))
print(os.path.isfile(paths[0]))
print('----------------------')
print(paths[1])
print(os.path.exists(paths[1]))
print(os.path.isdir(paths[1]))
#copy_path_file.close()
if os.path.exists(paths[0]):
if os.path.exists(paths[1]):
today = datetime.datetime.today()
date = str(today.year) + "." + str(today.month) + "." + str(today.day) + "-" + str(today.hour) + "." + str(today.minute)
index = paths[0].rfind('.')
#new_path = paths[0][0:index-1] + date + paths[0][index:paths[0].len]
#print(new_path)
print(paths[0])
#newPath = shutil.copy(paths[0], new_path)
我的问题是为什么
打印(os.path.exists(file_to_backup))
给我 true 但
打印(os.path.exists(路径[0]))
在同一路径上调用时返回 false ?
由于使用最小限度可重现的示例编写的代码并未询问我的问题,因此以下是较短的版本:
import os.path
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
file_to_backup = askopenfilename(title=' ')
print(os.path.exists(file_to_backup))
copy_path_file = open('copy_path.txt', 'w+')
copy_path_file.write(file_to_backup + '\n' + 'backup_directory')
copy_path_file.close()
copy_path_file = open('copy_path.txt', 'r')
paths = copy_path_file.readlines()
print(os.path.exists(paths[0]))
此打印返回true
但这将返回false,将file_to_backup路径写入文件,并且在从文件中读取路径之后,它将返回false。
用户jasonharper提供的答案是正确的,我必须从文件中读取路径后删除换行符号。