为什么我收到错误:"找不到这样的文件或目录"?



问题:当我试图将文本文件中的数据导入到python时,它说没有这样的文件或目录。我真的是一个初学者,所以如果有人能为我提供更好的代码来达到同样的目的,我会非常感激。

我想做的:在文本文件中接受用户的输入,并将字母"a"替换为"b"。然后,程序应该将文本文件中的输出提供给用户。

我的代码:

import os
texttofind = 'a'
texttoreplace = 'b'
sourcepath = os.listdir ('InputFiles')
for file in sourcepath:
inputfile = 'InputFiles' + file
with open(inputfile, 'r') as inputfile:
filedata = inputfile.read()
freq = 0
freq = filedata.count(texttofind)
destinationpath = 'OutputFIle' + file
filedata = filedata.replace(texttofind , texttoreplace)
with open(destinationpath,'w') as file:
file.write(filedata)
print ('the meassage has been encrypted.')

首先,我不会只使用"InputFiles";在os.listdir()中,但为相对路径或绝对路径

然后,当您得到所有的细分曲面时,您只得到名称:例如:";a"b"c〃。。。

这意味着,当您将源路径连接到文件时,您会得到类似于InputFilesa的内容,所以不是您要查找的文件。它应该看起来像:InputFiles/a

考虑到我告诉你的,现在你的代码应该是这样的:

import os

texttofind = 'a'
texttoreplace = 'b'
my_dir = "./InputFiles"
sourcepath = os.listdir(my_dir)
for file in sourcepath:
inputfile = my_dir + f"/{file}"
with open(inputfile, 'r') as inputfile:
filedata = inputfile.read()
freq = 0
freq = filedata.count(texttofind)
destinationpath = 'OutputFile' + f"/{file}"
filedata = filedata.replace(texttofind, texttoreplace)
with open(destinationpath,'w') as file:
file.write(filedata)
print ('the meassage has been encrypted.')

最新更新