我正在尝试获取此代码以获取文件,随机重命名它们并保存将随机名称与原始名称连接的密钥。最初,代码将获取所有文件(如计数器所示),并仅对其中的2/3执行脚本。现在,即使我使用绝对路径,它甚至都找不到我的目录。在Mac Mojave和python3.7上工作。
我尝试使用相对路径和绝对路径,并且在包含脚本和要在其上执行脚本的目录的目录中执行脚本。
#!/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")
它显示“失败”。
edit 我删除了撇号,并找到了目录,但是现在它不执行所有文件(仅重命名了81个文件中的50个)如下:
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))
```
答案 0 :(得分:0)
您正在检查是否存在名为“ path”的文件/路径。使用不带引号的变量名。例如
if os.path.exists('path'):
应该是
if os.path.exists(path):
答案 1 :(得分:0)
Dir = os.listdir(path)
print(Dir)
您可以直接打印Dir的大小以查看问题所在,
另一方面,为什么不尝试添加断点并自己查看Dir
中的内容。