Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python创建文件_Python - Fatal编程技术网

Python创建文件

Python创建文件,python,Python,这段代码应该用所有可能的字符f创建文件,然后当所有这些字符用于创建文件时,应该在第一个字符(f)中添加第二个字符(c),然后创建一个具有该名称的文件。这个程序似乎只创建两个字母的文件…撇开一个简单的事实不谈,代码从不检查终止(因此它永远运行),还有更好的方法来完成任务(排列),块 while True: rand = random.randint(70, 123) randomer = random.randint(70, 123) c = chr(randomer)

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

撇开一个简单的事实不谈,代码从不检查终止(因此它永远运行),还有更好的方法来完成任务(排列),块

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')
至少在两个方面似乎是错误的:

  • 您正在测试一条路径是否存在,并且您尝试(在teory中)创建另一条路径
  • os.path.exists(path)
    return false(第一次),因为该文件不存在,所以它不会创建该文件,因为您仅在该文件已经存在时才尝试创建该文件
  • 因此,更正确的代码可以是:

    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')
    

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

    请阅读-如何创建一个最小、完整且可验证的示例-
    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')