-1

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.')

  • Could you provide the full Traceback error? –  Jun 11 '22 at 14:55
  • A Traceback error in python is this: https://realpython.com/python-traceback/#what-is-a-python-traceback –  Jun 11 '22 at 15:03
  • you could try to use `os.path.join(foldername,filename)` to append the names cleanly – villanif Jun 12 '22 at 09:02
  • Your question says you need to read a single text file but the code attempts to read all files in a directory. What do you actually need to do? – interjay Jun 12 '22 at 09:15

1 Answers1

0

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.')
X1foideo
  • 46
  • 5