def downloadZipFromLink(dowLink, albumName):
    zipName = albumName.replace(" ", "") + ".zip"
    tempDir = tempfile.gettempdir();
    zipPath = os.path.join(tempDir, zipName)
    
    if (os.path.exists(zipPath)):
        print("Deleting zip which already exists at location '{}'".format(zipPath));
        os.remove(zipPath); 
    
    print("Downloading '{}' from '{}' to file '{}'".format(albumName, dowLink, zipPath))
    urlopener = URLopener();
    def reporthook(blocknum, blocksize, totalsize):
        readsofar = blocknum * blocksize
        if totalsize > 0:
            percent = readsofar * 1e2 / totalsize
            s = "\r%5.1f%% %*d / %d" % (
                percent, len(str(totalsize)), readsofar, totalsize)
            sys.stderr.write(s)
            if readsofar >= totalsize:  # near the end
                sys.stderr.write("\n")
        else:  # total size is unknown
            sys.stderr.write("read %d\n" % (readsofar,))  
    try:        
        urlopener.retrieve(dowLink, zipPath, reporthook)
    except:
        if (os.path.exists(zipPath)):
            print("\nDeleting archive file '{}'".format(zipPath));
            os.remove(zipPath); 
        raise;
    
    print("Download of '{}' has completed.".format(albumName))
    return zipPath;
 def removeFileIfExist(self,FileName):
         if os.path.exists(FileName):
             print("OTP File Exist")
             os.remove(FileName)
             print("Removed OTP file")
         else:    
             print("OTP File not Exist")
Esempio n. 3
0
def delete_file(filename):										# create function to delete a file
	if exists(filename):										# checks to see if file exists
		os.remove(filename)										# if it does, delete it
		print "\nYour file has been deleted!"
	else:														# if not, print that and set choice to blank to repeat loop
		print "\nThat file does not exist. Please try again.\n"
		choice = " "
def dowAndExtractZip(dowLink, albumName):
    if (not dowLink.endswith("zip")):
        print("Invalid download link '{}'".format(dowLink)); 
        return;   
    albumFolder = getAlbumFolder(albumName)
   
           
    if (os.path.exists(albumFolder)):
        if (not os.listdir(albumFolder)):
            os.rmdir(albumFolder);
        else:   
            print("\nAlbum '{}' already exists at location '{}'".format(albumName, albumFolder));
            return;
    
    zipFilePath = downloadZipFromLink(dowLink, albumName)
    os.makedirs(albumFolder)
    print("Extracting archive to folder".format(albumFolder));
    
    archive = zipfile.ZipFile(zipFilePath)
    for zipInfo in archive.filelist:
        songName = os.path.basename(zipInfo.filename);
        zipInfo.filename = songName;
        print("Extracting file '{}'".format(songName));
        archive.extract(zipInfo, albumFolder);
    archive.close();   
    
    print("Deleting archive file '{}'".format(zipFilePath));
    os.remove(zipFilePath); 
    print("\n***Album '{}' is created***".format(albumName));
Esempio n. 5
0
def __clear_outtime_code_func():
    """
    清除过期验证码
    """
    while (True):
        sleep(600)
        try:
            curr_time = time.time()
            logging.debug("---清除过期验证码")
            if False == os.path.isdir(yzm_path):
                continue
            fl = os.listdir(yzm_path)
            for f in fl:
                abs_f = yzm_path + f
                if True == os.path.isdir(abs_f):
                    print("文件夹  " + f)
                if True == os.path.isfile(abs_f):
                    upd_time = os.path.getmtime(abs_f)
                    if (curr_time - upd_time) > 600:
                        print("删除文件 : ", f, upd_time)
                        os.remove(abs_f)
                else:
                    print("err " + f)
        except Exception as e:
            logging.exception(e)
Esempio n. 6
0
    def tearDown(self):

        for metadata_file in self.metadata_files:
            metadata_file.close()

        for test_file_path in self.test_file_paths:
            if os.path.exists(test_file_path):
                os.remove(test_file_path)
Esempio n. 7
0
def remove_file(*files):
    import os
    yield
    for f in files:
        try:
            os.remove(f)
        except:
            pass
Esempio n. 8
0
def test_document_from_file(workspace, workspace_dir, cases):
    from os.path import os
    from robocorp_ls_core import uris
    from robocorp_ls_core.lsp import TextDocumentItem

    cases.copy_to("case1", workspace_dir)
    workspace.set_root(workspace_dir)

    ws = workspace.ws
    case1_file = os.path.join(workspace_dir, "case1.robot")
    assert os.path.exists(case1_file)

    case1_doc_uri = uris.from_fs_path(case1_file)
    resource_doc = ws.get_document(case1_doc_uri, accept_from_file=False)
    assert resource_doc is None

    cached_doc = ws.get_document(case1_doc_uri, accept_from_file=True)
    assert cached_doc is not None
    assert "*** Settings ***" in cached_doc.source

    with open(case1_file, "w") as stream:
        stream.write("new contents")
    assert "*** Settings ***" in cached_doc.source  # i.e.: Unchanged

    # When we get it again it verifies the filesystem.
    cached_doc2 = ws.get_document(case1_doc_uri, accept_from_file=True)
    assert cached_doc is not cached_doc2

    # i.e.: Unchanged initial version in memory
    assert "*** Settings ***" in cached_doc.source
    assert cached_doc2.source == "new contents"

    # Still None if we can't accept cached.
    resource_doc = ws.get_document(case1_doc_uri, accept_from_file=False)
    assert resource_doc is None

    ws.put_document(TextDocumentItem(case1_doc_uri, text="rara"))
    resource_doc = ws.get_document(case1_doc_uri, accept_from_file=False)
    assert resource_doc is not None
    assert resource_doc is not cached_doc

    ws.remove_document(case1_doc_uri)
    resource_doc = ws.get_document(case1_doc_uri, accept_from_file=False)
    assert resource_doc is None
    cached_doc3 = ws.get_document(case1_doc_uri, accept_from_file=True)
    assert cached_doc3 is not None

    # i.e.: it should've been pruned when the doc was added.
    assert cached_doc3 is not cached_doc
    assert cached_doc3.source == "new contents"

    os.remove(case1_file)
    cached_doc4 = ws.get_document(case1_doc_uri, accept_from_file=True)
    assert cached_doc4 is None

    # The old one in memory doesn't change after the file is removed
    assert cached_doc3.source == "new contents"
Esempio n. 9
0
def test_readwrite():
    import ubelt as ub
    dpath = ub.ensure_app_cache_dir('ubelt')
    fpath = dpath + '/' + 'testwrite.txt'
    if exists(fpath):
        os.remove(fpath)
    to_write = 'utf-8 symbols Δ, Й, ק, م, ๗, あ, 叶, 葉, and 말.'
    ub.writeto(fpath, to_write, verbose=True)
    read_ = ub.readfrom(fpath, verbose=True)
    assert read_ == to_write
Esempio n. 10
0
 def testName(self):
     
     runner=CliRunner()
     try:
         os.remove('prerequisites-v1.out')
     except:
         pass
     result=runner.invoke(arcup.create,['update-v1.1.zip','v1.zip','v1.1.zip' ,'prerequisites-v1.out', '--ignore-patterns-list', 'ignored_files'])
     self.assertEqual(result.exit_code, 0)
     #arcup.create(click.path("update-v1.1.zip"),"v1.zip", "v1.1.zip" ,"prerequisites.txt")
     self.assertTrue(filecmp.cmp('prerequisites-v1.out','requisites-v1.1.ref'))
Esempio n. 11
0
def removeFile(name):
    """
                删除上传的文件,仅限upload里面的
                创建:2014年10月15日上午11:45:55 李鹏飞
                更新:2014年10月15日上午11:45:55 李鹏飞
        :param: name:图片路径(数据库里存的)如:/upload/replyimg/...
        :return: 
        :rtype: 
    """
    try:
        os.remove(os.path.join(settings.MEDIA_ROOT, name.replace(settings.MEDIA_URL, "")))
    except WindowsError:
        logger.warning(u"删除文件[%s]失败" % name)
Esempio n. 12
0
 def calculating_incremental(self, name, message):
     self.log.info("calculating")
     self.settings["Name"] = name
     self.download_sounds()
     if os.path.isfile(self.file_system.path+"/"+name+".logs/output.txt"):
         os.remove(self.file_system.path+"/"+name+".logs/output.txt")
     self.precise_calc = subprocess.Popen([self.file_system.path+"/precise/.venv/bin/python "+
                                 self.file_system.path+"/precise/precise/scripts/train-incremental.py "+
                                 self.file_system.path+"/"+name+".net "+
                                 self.settings["file_path"]+name],
                                 preexec_fn=os.setsid, stdout=subprocess.PIPE, shell=True)
     self.schedule_repeating_event(self.precise_calc_check, None, 3,
                                       name='PreciseCalc')
     return True
Esempio n. 13
0
def apply(update_archive_filename,target_directory,prerequisites_file):
    print "Checking prerequisites..."
    check_errors=0
    prerequisites= json.load(prerequisites_file)
    presence_requirements=[requirement for requirement in prerequisites if requirement['require_type']=='present']
    files_to_remove=[requirement['file'] for requirement in prerequisites if requirement['require_type']=='to_remove']
    for prerequisite in presence_requirements:
        file_name=prerequisite['file']
        installed_file=os.path.join(target_directory,file_name)
        same_file=True
        current_filesize=-1
        try:
            current_filesize=os.path.getsize(installed_file)
        except:
            pass
        if current_filesize!=prerequisite['size']:
            print >> stderr, "ERROR :  '{}' ==>   expected size = {}  real size = {}".format(installed_file,prerequisite['size'],current_filesize)
            same_file=False
        else:
            BLOCKSIZE = 65536
            hasher = hashlib.md5()
            with open(installed_file, 'rb') as afile:
                buf = afile.read(BLOCKSIZE)
                while len(buf) > 0:
                    hasher.update(buf)
                    buf = afile.read(BLOCKSIZE)
            real_md5=hasher.hexdigest()
            if real_md5!=prerequisite['md5']:
                same_file=False
                print >> stderr, "ERROR :  '{}' ==>   expected md5 = {}  real md5 = {}".format(installed_file,prerequisite['md5'],real_md5)
            
        if not same_file:
            print >> stderr, "ERROR : installed file '{}' is not of the expected version.".format(installed_file)
            check_errors+=1
    if check_errors != 0:
        print >>    stderr, "ERROR : {} installed file(s) do not match expected version ==> will not apply patch.".format(check_errors)
        return 13
    print "All required installed files are matching expected version. Proceeding with patch..."
    for file in files_to_remove:
        if os.path.isfile(file):
            os.remove(file)
    with zipfile.ZipFile(update_archive_filename) as updatezip:
        updatezip.extractall(target_directory)
Esempio n. 14
0
 def improve_intent(self, message):
     name = self.config_core.get('listener', {}).get('wake_word').replace(' ', '-')
     i = 1
     if os.path.isdir(self.settings["sell_path"]):
         onlyfiles = next(os.walk(self.settings["sell_path"]))[2]
         if len(onlyfiles) <= self.settings["improve"]:
             selling = len(onlyfiles)
         else:
             selling = self.settings["improve"]
         self.speak_dialog('improve', data={'name': name, "selling": selling})
         self.log.info("search wake word in: "+self.settings["sell_path"])
         wait_while_speaking()
         for root, dirs, files in os.walk(self.settings["sell_path"]):
             for f in files:
                 filename = os.path.join(root, f)
                 if filename.endswith('.wav'):
                     if i <= selling:
                         self.log.info("play file")
                         play_wav(filename)
                         wait_while_speaking()
                         time.sleep(3)
                         sell = self.ask_yesno("ask.sell", data={'i': i})
                         wait_while_speaking()
                         i = i+1
                         path = None
                         if sell == "yes":
                             path = self.settings["file_path"]+name+"/wake-word/"+self.lang[:2]+"-short/"
                         elif sell == "no":
                             path = self.settings["file_path"]+name+"/not-wake-word/"+self.lang[:2]+"-short-not/"
                         if not path is None:
                             if not os.path.isdir(path):
                                 os.makedirs(path)
                             file = path+name+"-"+self.lang[:2]+"-"+str(uuid.uuid1())+".wav"
                             shutil.move(filename, file)
                             self.log.info("move File: "+file)
                         else:
                             os.remove(filename)
         else:
             self.speak_dialog('improve.no.file', data={'name': name})
     else:
         self.speak_dialog('improve.no.file', data={'name': name})
Esempio n. 15
0
        def check_perf_for_obj(self, a):
            import cProfile as profile
            import pstats
            stats = 'profile_log_txt'
            profile.runctx(
                '''
    for x in range(100000):
        a.update("/project/path/test/a/" + str(x))
    b = a.hexdigest()
    ''', globals(), locals(), stats)
            p = pstats.Stats(stats)
            p.sort_stats('cumulative').print_stats(100)
            os.remove(stats)

            try:
                from pympler import asizeof  # @UnresolvedImport
                print('Size of object:', asizeof.asizeof(a))
                print()
            except:
                pass
            expected = 'fe01e1389b43d115fb6b8f9a13eee937b599eebf4d4fac33866741bd33819466c38dc8c2cabdeb415179bb9fcff570d57d8ea80db21def5ebe7cc4b1b078c1e7'
            assert expected == a.hexdigest()
Esempio n. 16
0
# Open a File
file = open(file="text.txt", mode='wb', buffering=1)
print("Name of the title: ", file.name)
print("Closed or not: ", file.closed)
print("Opening mode: ", file.mode)
file.write(
    bytes("I am not a psychopath, I am a high functioning sociopath.\n",
          "UTF-8"))
file.close()

file = open(file="text.txt", mode="r", buffering=1)
print("Position: ",
      file.tell())  # Tell the position of the current seeking point.
data = file.read()  # Read all bytes
file.close()
print("The read data is: ", data)
print("Closed or not: ", file.closed)

# Use the OS path library.
os.rename("text.txt", "newText.txt")  # Rename the file name.
os.remove("newText.txt")  # Remove the file with this file name.
os.mkdir("folder", mode=0o777)
os.chdir("folder")
# Changes the current directory with this.
os.mkdir("test")  # Makes folder in folder with name test.

print("The current dir: ", os.getcwd())  # Prints the current directory path.
os.rmdir("folder")
# Removes the directory.
from os.path import expanduser, os
import time, subprocess, wget, os
print('SCRIPT BY ANDREI ZHUK')
time.sleep(1)
print('https://vk.com/andrey47785')
#НЕ ВОЛНУЙТЕСЬ ПО ПОВОДУ ТОГО,ЧТО МОДУЛИ НЕ БУДУТ ИМПОРТИРОВАТСЯ ПОТОМУЧТО ЗА ВАС ЭТО СДЕЛАЕТ И ЗАПАКУЕТ В ПРОГРАММУ МОДУЛИ ПАЙ ИНСТАЛЛ
home = expanduser("~")
time.sleep(1.56)
print('Закачиваю файлы...')
time.sleep(1)
print('.\\WHAIT//.')
s = 'https://www.python.org/ftp/python/3.8.7/python-3.8.7rc1-amd64.exe'
filename = wget.download(s)
os.rename(filename, u'' + os.getcwd() + '/' + filename)
subprocess.call([home + '/Desktop/python-3.9.1-amd64.exe'])
print('OK')
os.remove(home + '/Desktop/python-3.9.1-amd64.exe')
print('DELETED TO INSTALATOR')
time.sleep(3)
print('УДАЛЯЮ СЕБЯ...')
os.remove(home + '/Desktop/installpythonby.exe')
Esempio n. 18
0
def deleteFile(file):
    os.remove(file)
    print("Removed file")
    checkFileExist(file)
Esempio n. 19
0
def deleteFile(filename):
    """Delete a file gracefully, first checking that it exists."""
    if os.path.exists(filename) and os.path.isfile(filename):
        os.remove(filename)
Esempio n. 20
0
 def clear(self, bucket_name):
     check_valid_bucket_name(bucket_name)
     with timed_acquire_mutex(_get_mutex_name(bucket_name)):
         contents_file = self._get_contents_file(bucket_name)
         if os.path.exists(contents_file):
             os.remove(contents_file)
Esempio n. 21
0
fo.write( "Python is a great language.\nYeah its great!!\n");

# 关闭打开的文件
fo.close()

fo = open(pathfile, "r+");

strRead = fo.read(30);
print (strRead)

strReada = fo.read();
print (strReada);

fo.close();
#remove()方法删除文件,需要提供要删除的文件名作为参数。
os.remove("foo1.txt");
#rename()方法需要两个参数,当前的文件名和新文件名。
os.renames("foo.txt", "foo1.txt");

#可以使用os模块的mkdir()方法在当前目录下创建新的目录们。你需要提供一个包含了要创建的目录名称的参数
os.mkdir("test");
#可以用chdir()方法来改变当前的目录。chdir()方法需要的一个参数是你想设成当前目录的目录名称。
os.chdir("test")
#getcwd()方法显示当前的工作目录。
# 给出当前的目录
print  (os.getcwd());


#os.removedirs("")

Esempio n. 22
0
 def clear(self, bucket_name):
     check_valid_bucket_name(bucket_name)
     with timed_acquire_mutex(_get_mutex_name(bucket_name)):
         contents_file = self._get_contents_file(bucket_name)
         if os.path.exists(contents_file):
             os.remove(contents_file)