May-06-2022, 12:25 PM
I have a folder with .txt files. In that folder I want to list all the files and read each files and replace a specific String. The problem I get is that the error message is telling me there is no such file or directory which are strange since I can list the files with a print. The "test2.txt" that are listed in my error message is just one of the files in that specific folder.
This is my code:
What I would like to achive is to understand why I got this error message. Dont get it. And if possible get some feedback of the code if I have the correct approach.
This is my code:
import os
#declare my folder
ws_folder =r"C:\FMEData\test"
#declare what to replace
search_text = "FMEData2019"
replace_text = "FMEData"
#list files in directory
listdir=os.listdir(ws_folder)
#printing files in directory for check
print (listdir)
for file in listdir:
#checking if i can print the files
print(file)
#Open each file as read mode
openfile= open(file,"rt")
#read each opened file
data=openfile.read()
#replace text for each opened file
data = data.replace('search_text', 'replace_text')
#close the file
openfile.close()
#the open file as write mode
openfile = open("file", "wt")
openfile.write(data)
openfile.close()And this is my error message:Error: openfile= open(files,"rt")
FileNotFoundError: [Errno 2] No such file or directory: 'test2.txt'I hope this question is correcly made since I am new to booth python and this forum. What I would like to achive is to understand why I got this error message. Dont get it. And if possible get some feedback of the code if I have the correct approach.
