Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Why it doesnt open the file ? if it read the name and extension correctly

Eshu

Coder
Hello people,

Im doing a little script in python to practice.
Is a recursive method, it read the folder and files in a directory.

If its a file and ends with ".txt", read the file a look for a word in each line, if it find it, write the line in an other file.
If its a folder, calls it self to do the same process.

Here is the code:
[CODE lang="python" title="Script"]import os

def scan_folder(parent):

#List the directories and files
for file_name in os.listdir(parent):
#If its a file that end in '.txt', read it
if file_name.endswith(".txt"):
#The line bellow give the error
thing = open(file_name, "r")
for line in thing:
if line.find('test') >= 0:
my_method(line)
#If not call it self
else:
current_path = "".join((parent, "/", file_name))
if os.path.isdir(current_path):
scan_folder(current_path)

#Takes the line and write it
def my_method(linea):
file = open('C:/Users/Eshu/Desktop/thing.txt', "a")
file.write(linea + "\r")
file.close()

scan_folder('C:/Users/Eshu/Desktop/Test')[/CODE]

It gives me the next error:

Traceback (most recent call last):
File "C:/Users/Eshu/Desktop/untitled-3.py", line 24, in <module>
scan_folder('C:/Users/EdU/Desktop/Test')
File "C:/Users/Eshu/Desktop/untitled-3.py", line 16, in <module>
scan_folder(current_path)
File "C:/Users/Eshu/Desktop/untitled-3.py", line 16, in <module>
scan_folder(current_path)
File "C:/Users/Eshu/Desktop/untitled-3.py", line 8, in <module>
thing = open(file_name, "r")
builtins.FileNotFoundError: [Errno 2] No such file or directory: 'my_file.txt'

Im trying to solve it, but i couldn´t find the mistake. I made it simple, but nothing work.
I know the file exist, i create it, and the error is given in the line 8

[CODE lang="python" title="Error line"]thing = open(file_name, "r")[/CODE]


Thanks you guys
 
When the path is relative, you must write its path relatively to the position of the script, so in your case it should be '../my_file.txt'. '../' simply means "Go back to the parent folder".
 

New Threads

Buy us a coffee!

Back
Top Bottom