Python创建文件

时间:2015-04-30 18:55:25

标签: python

while True:
    rand = random.randint(70, 123)
    randomer = random.randint(70, 123)
    c = chr(randomer)
    f = chr(rand)
    f = f
    path = os.path.join(r'D:\Python\New folder', f)
    secondPath = os.path.join(r'D:\Python\New folder', f+c)
    thirdPath = os.path.join(r'D:\Python\New folder', f+c+'INTERWABZ.CC')
#'.exe'
    if '\\' in f :
        continue

    elif '\\' in c:
        continue
    open(f, 'w')


    if os.path.exists(path):
        open(f+c, 'w')
    elif os.path.exists(secondPath):
        open(f+c+'INTERWABZ.CC', 'a')
    elif os.path.exists(thirdPath):
        open(f+c+'.exe', 'a')

这段代码应该创建所有可能的字符为f的文件,然后当所有这些字符用于创建文件时,第二个字符(c)应该被添加到第一个字符(f)然后创建一个具有该名称的文件。这个程序似乎只创建两个字母的文件......

1 个答案:

答案 0 :(得分:0)

除了一个简单的事实,即代码永远不会检查终止(因此它会永远运行)并且有更好的方法来完成工作(排列),块

if os.path.exists(path):
    open(f+c, 'w')
elif os.path.exists(secondPath):
    open(f+c+'INTERWABZ.CC', 'a')
elif os.path.exists(thirdPath):
    open(f+c+'.exe', 'a')

似乎至少有2个错误:

  1. 您正在测试路径是否存在并且您尝试(在teory中)创建另一条路径
  2. os.path.exists(path)返回false(第一次),因为该文件不存在,然后它不会创建该文件,因为您只是在它已经存在时才尝试创建该文件。
  3. 所以更正确的代码可以是:

    if not os.path.exists(path):
        open(path, 'w')
    elif not os.path.exists(secondPath):
        open(secondPath, 'a')
    elif not os.path.exists(thirdPath):
        open(thirdPath, 'a')
    

    创建了所有文件,但仍然存在while永远不会结束的问题。