Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.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_If Statement_Rename - Fatal编程技术网

如何检查文件是否存在,如果存在,请在python中重命名它

如何检查文件是否存在,如果存在,请在python中重命名它,python,if-statement,rename,Python,If Statement,Rename,我正在寻找一种更具python风格的方法来完成我的代码目前所做的事情。我相信有更好的办法。我想搜索到filename-10,如果存在,创建一个名为filename-11的文件 如果你能帮忙,那就太好了 编辑:2014年9月1日晚上9:46 import re import os f=open('/Users/jakerandall/Desktop/Data Collection Python/temp.cnc', 'r') text = re.search(r"(?<!\d)\d{4,5}

我正在寻找一种更具python风格的方法来完成我的代码目前所做的事情。我相信有更好的办法。我想搜索到filename-10,如果存在,创建一个名为filename-11的文件

如果你能帮忙,那就太好了

编辑:2014年9月1日晚上9:46

import re
import os
f=open('/Users/jakerandall/Desktop/Data Collection Python/temp.cnc', 'r')
text = re.search(r"(?<!\d)\d{4,5}(?!\d)", f.read())
JobNumber = text.string[text.start():text.end()]


if os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-10.cnc" % JobNumber):
    f=open("/Users/jakerandall/Desktop/Data Collection Python/%s-11.cnc"  % JobNumber, 'w+b')
    f.close()
    print '1'
elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-9.cnc" % JobNumber):
    f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-10.cnc' % JobNumber, 'w+b')
    f.close()
    print '2'
elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-8.cnc" % JobNumber):
    f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-9.cnc' % JobNumber, 'w+b')
    f.close()
    print '3'
elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-7.cnc" % JobNumber):
    f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-8.cnc' % JobNumber, 'w+b')
    f.close()
    print '4'
elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-6.cnc" % JobNumber):
    f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-7.cnc' % JobNumber, 'w+b')
    f.close()
    print '5'
elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-5.cnc" % JobNumber):
    f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-6.cnc' % JobNumber, 'w+b')
    f.close()
    print '6'
elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-4.cnc" % JobNumber):
    f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-5.cnc' % JobNumber, 'w+b')
    f.close()
    print '7'
elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-3.cnc" % JobNumber):
    f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-4.cnc' % JobNumber, 'w+b')
    f.close()
    print '8'
elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-2.cnc" % JobNumber):
    f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-3.cnc' % JobNumber, 'w+b')
    f.close()
    print '9'
elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-1.cnc" % JobNumber):
    f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-2.cnc' % JobNumber, 'w+b')
    f.close()
    print '10'
elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s.cnc" % JobNumber):
    f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-1.cnc' % JobNumber, 'w+b')
    f.close()
    print '11'
else:
    f=open('/Users/jakerandall/Desktop/Data Collection Python/%s.cnc' % JobNumber, 'w+b')
    f.close()
    print '12'
f.close()
重新导入
导入操作系统
f=打开('/Users/jakerandall/Desktop/Data Collection Python/temp.cnc','r')

text=re.search(r)(?简单一点怎么样:

import glob

file_directory = '/Users/jakerandall/Desktop/Data Collection Python/'
files = glob.glob('{}{}*.cnc'.format(file_directory, JobNumber))
现在,
文件
将是目录中实际存在并与您的模式匹配的文件名列表

您可以检查此列表的长度,然后:

  • 如果为空,则创建第一个文件,即
    '{}.cnc'.format(JobNumber)
  • 如果列表长度等于11,则需要创建文件编号11(因为模式将匹配第一个文件,即没有任何
    -
    ,因此长度为11表示最后一个文件为
    -10.cnc
  • 否则,您需要的文件是列表长度的1。因此,如果列表有5项,则表示最后一个文件是
    -4.cnc
    (因为模式也将匹配第一个文件)
  • 您仍然需要查看是否可以打开它们,因为运行Python脚本的用户可能没有足够的权限

    下面是一个将所有这些放在一起的示例:

    import glob
    
    file_directory = '/Users/jakerandall/Desktop/Data Collection Python/'
    files = glob.glob('{}{}*.cnc'.format(file_directory, JobNumber))
    
    # Start by assuming there are no files:
    filename = '{}.cnc'.format(JobNumber)
    if len(files) <= 11:
       # If there are less than 11 files, we need
       # to use the existing file, and overwrite it
       # If there are 4 files, in the directory, our
       # list will have a length of 5:
       # The original file, and then four files from -1, to -4
       # In this case, we want to use file 4, which is 1 less than
       # the length of the list:
       filename = '{}-{}.cnc'.format(JobNumber, len(files)-1)
    else:
       # If we reach this point, it means
       # there were more than 10 files that match the
       # pattern. We want to use the next file,
       # which is next number higher, which is also the length
       # of the list, since it will include the first file.
       # So if the last file is -20, the list will have 20 files (from -1, to -20)
       # plus the original file, which has no - in the filename, giving
       # a length of 21, which also happens to be the number of the file
       # we want to create :)
       filename = '{}-{}.cnc'.format(JobNumber, len(files))
    
    # Now, try to create the file
    try:
       f = open(filename, 'w+b')
    except IOError:
       print('Cannot create {}, check permissions?'.format(filename)) 
    
    导入全局
    file_directory='/Users/jakerandall/Desktop/Data Collection Python/'
    files=glob.glob('{}{}*.cnc'.格式(文件目录,作业编号))
    #首先假设没有文件:
    文件名=“{}.cnc.”格式(作业编号)
    
    如果len(files)我实际上写过这样的东西!不过我是从内存中工作的。这作为一个单独的模块很有用,因为以这种方式备份文件是相当常见的

    # /backup_dash_one.py
    
    import os, glob, re
    
    def backup(full_path, num_backups=None):
        """Usage: backup('example/pathname.ext', [num_backups])
        returns: example/pathname-1.ext, advances all backups by 1
    
        Given example/pathname.ext, creates backups named
        example/pathname-1.ext, -2.ext, -3.ext until there are
        as many backups as num_backups, purging those older."""
    
        head, tail = os.path.split(full_path)
        tailname, tailext = os.path.splitext(tail)
    
        def find_backup_num(path):
            return int(re.search(r"-(\d+)\.[^.\\/]*", path).group(1))
    
        paths = sorted(glob.glob(os.path.join(head,tailname)+"-*"+tailext),
                       key=find_backup_num)
        for path in reversed(paths[:]):
            head_tail, backup_num, ext, _* = re.split(r"-(\d+)(\.[^\\./]*)$", path)
            new_path = head_tail + "-" + str(int(backup_num)+1) + ext
    
            with open(path) as infile, open(new_path,'w') as outfile):
                for line in infile:
                    outfile.write(line)
            if new_path not in paths:
                paths.append(new_path)
    
        while num_backups and len(paths) > num_backups:
            os.remove(paths[-1])
            paths.pop()
    
    就我个人而言,如果我有时间,我真的应该致力于此,我会做更多的研究,并做一些类似的事情:

    import glob, os
    
        class BackupFile(object):
        def __init__(self, path, mode="w", num_backups=None):
            self.num_backups = num_backups
            path_filename, ext = os.path.splitext(path)
            self.backups = glob.glob(path_filename+"-*"+ext)
            self.backups.sort(key=self.find_backup_num)
            self.backup()
            self.purge()
            with open(path_filename+"-1"+ext, 'w') as backup,\
                 open(path, 'r') as original:
                for line in original:
                    backup.write(line)
            self.f = open(path, mode)
    
        def find_backup_num(self,filename):
            return int(os.path.splitext(filename)[0].split('-')[-1])
        def backup(self):
            for path in reversed(self.backups[:]):
                head_num,ext = os.path.splitext(path)
                *head,num = head_num.split('-')
                new_path = "{}-{}{}".format('-'.join(head),
                                int(num)+1,
                                ext)
                with open(new_path, 'w') as newfile, \
                     open(path, 'r') as oldfile:
                    for line in oldfile:
                        newfile.write(line)
                if new_path not in self.backups:
                    self.backups.append(new_path)
        def purge(self):
            while self.num_backups and len(self.backups) > self.num_backups:
                os.remove(self.backups.pop())
        def __enter__(self):
            return self.f
        def __exit__(self, exc_type, exc_value, exc_traceback):
            self.f.close()
    
    所以你可以这样做:

    with BackupFile("path/to/file/that/needs/backups.txt", 'r+', num_backups=12) as f:
        make_change(f)
    # ta-da it's backed up!
    

    但是,我根本没有机会测试它,所以我猜它有很大的问题:)

    在每种情况下,您都将
    %JobNumber
    放在括号外,这不会将其插入“%s”中“。这可能不是您想要做的。如果您打算按顺序写入下一个编号的文件,您可能应该a)检查该目录中编号最大的文件,然后b)将该编号递增1并打开它(而不是所有这些废话);)大卫-我才意识到。谢谢你指出这一点。你可以说,python还是个新手,哈哈。乔尔-这正是我想做的我只是不知道该怎么做谢谢你的帮助。我了解一点,但不是全部。我对python还是很陌生。我编辑了我的文章来展示我的代码的其余部分,如果你不介意给我一些关于正确编写脚本的指导,我将非常感激。我被困在你名单上的“我该怎么做”上了。我需要创建一个if语句,我猜?