Problem: When I try to import data from a text file to python it says no such file or directory. I really am a beginner so I would really appreciate it if someone could provide me with better code for the same purpose.
What I want to do: take input from the user in a text file and replace the letter 'a' with 'b'. The program should then give the output in a text file to the user.
My code:
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.')
CodePudding user response:
First of all I wouldn't use only "InputFiles" in os.listdir(), but a Relative or Absolute Path.
Then when you get all the subdirs, you get only the names: eg: "a", "b", "c", ...
This means that whent you concatenate sourcepath to file you get something like InputFilesa so not the file you were looking for. It should look like: InputFiles/a
Taking into consideration what I told you, now your code should look like:
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.')