2014-09-02 3 views
0

나는 현재 내 코드가하는 일을 수행하기위한 더 파이썬적인 방법을 찾고있다. 나는 이것을 할 수있는 더 좋은 방법이있을 것이라고 확신한다. filename-10까지 검색하고 싶다면 filename-11이라는 파일을 만듭니다.파일이 존재하는지 확인하는 방법 파이썬에서 이름을 바꾼다.

도움이 될 수 있다면 도움이 될 것입니다.

편집 : 9/1/14 오후 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() 
+1

이 경우 각각 괄호의'% JobNumber' *를 쓰지 않고 * % *에 삽입하지 않을 것입니다. 이것은 아마도 당신이하고자하는 것이 아닙니다. –

+0

만약 * next * 번호가 매겨진 파일을 순서대로 쓰고 싶다면 a) 그 디렉토리에서 최대 번호가 매겨진 파일을 확인한 다음 b) 그 번호를 하나씩 늘리고 열어 라.) –

+0

David - 방금 깨달았습니다. 그 점을 지적 해 주셔서 감사합니다. 하하에게 말할 수있는 것처럼 아직 파이썬에 대한 새로운 지식은 없습니다. Joel - 정확히 내가하려고하는 것 나는 단지 어떻게 해야할지 모르겠다. –

답변

1

방법은 간단에 대해 뭔가 :

import glob 

file_directory = '/Users/jakerandall/Desktop/Data Collection Python/' 
files = glob.glob('{}{}*.cnc'.format(file_directory, JobNumber)) 

지금 files 실제로 디렉토리에 존재하는 파일 이름의 목록이 될 것이며, 당신의 패턴을 일치시킵니다.

이 목록의 길이를 확인하고 있습니다 :

  1. 를 그 빈, 그냥 '{}.cnc'.format(JobNumber) 첫 번째 파일을 만들 수 있습니다.
  2. 목록의 길이가 11이면 패턴 번호가 -이 아닌 첫 번째 파일과 일치하므로 길이가 11 인 경우 마지막 파일이 -10.cnc 인 파일 번호 11을 만들어야합니다.
  3. 그렇지 않으면 원하는 파일의 길이는 1입니다. 따라서 목록에 5 개의 항목이있는 경우 마지막 파일은 -4.cnc입니다 (패턴이 첫 번째 파일과 일치하기 때문에).

파이썬 스크립트를 실행하는 사용자에게 충분한 권한이 없기 때문에 열 수 있는지 확인해야합니다.

는 여기에 예제가 모두 함께 넣어이다 : 나는 사실 이런 식으로 뭔가를 작성했습니다

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)) 
+0

도움을 주셔서 감사합니다. 나는 이것의 약간을 이해한다. 그러나 그것의 전부는 아니다. 임씨는 여전히 파이썬에 대해 아주 새롭다.내 코드의 나머지 부분을 보여주기 위해 내 게시물을 편집했습니다. 스크립트 작성에 대한 지침을 좀 더 알려 주시면 감사하겠습니다. 귀하의 목록에서 어떻게해야합니까? 내가 추측하고있는 if 문을 작성해야합니까? –

0

! 나는 기억에서 일하고있다. 이 방법으로 파일을 백업하는 것이 매우 일반적이므로 별도의 모듈로 유용합니다. 내가 좋아하는 뭔가 내가 좀 더 연구를 할 것이에 정진 할 수있는 정말한다고 시간이 있었다 개인적으로 경우

# /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! 

그러나 나는 그걸 전혀 테스트 할 기회가별로 없기 때문에 내 생각에 뭔가 잘못된 것이 있습니다.

관련 문제