-2

1.) I am trying to search for a file hello.py, and return the string in python3 The file path is /Users/Joshua/Appdata/Local/Programs/Python/Python38/User_code/Hello.py but instead the code returns tons of: {print("file not here")}

2.)I can't run hello.py atm, cause idk - (1)im not in right directory (2)idk if its module/or script (3)first time in python and im new to it.

3.) how should i have set up python to cause less headache??? should i have installed it to /Users/Joshua/ >>>> to cause less headache ?? how did you make it easier for you to learn?

PS: first question im asking on stack overflow...Hooray

import os
File = 'hello.py'
for root, dirs, files in os.walk('/Users/Joshua/Appdata/Local/Programs/Python/Python38/'):  
    if File in files:
        print ("File exists")
    if File not in files:
        print("file not here")
Yeganeh Salami
  • 575
  • 7
  • 29
J J
  • 1
  • 2

3 Answers3

0
import os

file_name = "hello.py"
cur_dir = 'C:/Users/Joshua/Appdata/Local/Programs/Python/Python38/'

file_list = os.listdir(cur_dir)
if file_name in file_list:
    print("File Exists")
else:
    print("File not here")
0

Call print only when you have a match

import os
File = 'forex.py'
for root, dirs, files in os.walk(os.path.normpath('C:/Users/asus/Desktop/')):  
    if File in files:
        print (os.path.join(root, File))
    # if File not in files:
        # print("file not here")
0

Try this:

from pathlib import Path

if Path('./Users/Joshua/Appdata/Local/Programs/Python/Python38/').glob('**/hello.py'):
    print('File exists')
else:
    print('File does not exist')
goodvibration
  • 5,980
  • 4
  • 28
  • 61