简体   繁体   中英

Python script can't find path using os.path.exists tool even though the absolute path is being used

I'm trying to get this code to take files, rename them randomly, and save a key connecting the random names to the original names. At first the code was taking all of the files (as indicated by the counter) and executing the script on only about 2/3 of them. Now, it is not even finding my directory even though I am using the absolute path. Working on Mac Mojave and python3.7.

I have tried using the relative as well as the absolute path and am executing the script in the terminal when I am in the directory which contains both the script and the directory I want to execute it on.

#!/usr/bin/env python3

#This program takes files in a directory and renames them as a random number, this random number can be connected
#to the original file as the pairs are stored in a dictionary named key, can be used for blind analysis

import os
import random
import json
import shutil


path = "/Users/krisshirley108/pcfb/bookscripts/8.1schmoocopy/"

if os.path.exists('path'):


  Dir = os.listdir('path') 

  Key = {}

  counter = 0

  for File in Dir:
    print (File) 

    counter = counter + 1

  print (counter)

else:
  print ("failed")

It prints 'failed'.

edit I removed the apostrophes and it found the directory but now it is not executing all of the files (only renames 50 out of 81) the rest of the code is as follows:

if os.path.exists(path):


  Dir = os.listdir(path) 

  Key = {}

  counter = 0

  for File in Dir:
    print (File) 
    #chooses a number in the range 1-100 and assigns it as variable new name
    newname = str(random.randint(1,100))

    #takes name of original file and makes key with new file name in dictionary named Key
    Key[File] = newname

    os.rename('/Users/krisshirley108/pcfb/bookscripts/8.1schmoocopy/' + File , newname)

    counter = counter + 1

  print (counter)


  #open the file in the mode that allows you to write to it (w) and (+) ensures you can read it too
  cheatsheet = open("cheatsheet.txt" , 'w+')

  #makes a new text file, names it cheat sheet, json helps open complex things ie the dictionary
  with open("cheatsheet.txt" , 'w') as file:
    file.write(json.dumps(Key))

    ``` 

You are checking the existence of a file/path named "path". Use the variable name without quotes. Eg

if os.path.exists('path'):

Should be

if os.path.exists(path):
Dir = os.listdir(path) 
print(Dir)

you can directly print the size of Dir to see what is wrong,

On the other side, why not try to add a breakpoint and see what in the Dir yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM