本文整理汇总了Python中FileUtils类的典型用法代码示例。如果您正苦于以下问题:Python FileUtils类的具体用法?Python FileUtils怎么用?Python FileUtils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FileUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: antFileAction
def antFileAction(path, key, action, value = "1"):
antFile = path + s_antPath
fp = open(antFile, "r")
str = fp.read()
fp.close()
#查找的位置
findKeyIndex = str.find(key)
#没有找到,直接退出
if findKeyIndex == -1:
print antFile,"Not Found",key
return
index = len(key)
#取到开始的字符
lastText = str[0 : findKeyIndex + index]
#取到之后的字符
nextText = str[findKeyIndex + index: ]
#查找下一个回车
nexiIndex = nextText.find("\n")
#分割下个字符串
if -1 == nexiIndex:
nexiIndex = len(nextText)
#剩下的就是version
findValue = nextText[0 : nexiIndex]
if action == s_getAction:
return findValue
elif action == s_wirteAction:
valueNextText = nextText[nexiIndex: ]
text = lastText + "=" + value + valueNextText
FileUtils.writeFile(antFile , text)
示例2: readMusicFile
def readMusicFile(_filePath, _isAlertWhenNotAvailable=True):
_directoryPath = fu.getDirName(_filePath)
isCanNoncompatible = False
if fu.isReadableFileOrDir(_filePath):
tagger = Taggers.getTagger()
try:
tagger.loadFile(_filePath)
except:
Dialogs.showError(translate("FileUtils/Musics", "Incorrect Tag"),
str(translate("FileUtils/Musics",
"\"%s\" : this file has the incorrect tag so can't read tags.")
) % Organizer.getLink(_filePath))
if tagger.isAvailableFile() is False:
isCanNoncompatible = True
content = {}
content["path"] = _filePath
content["baseNameOfDirectory"] = fu.getBaseName(_directoryPath)
content["baseName"] = fu.getBaseName(_filePath)
content["artist"] = tagger.getArtist()
content["title"] = tagger.getTitle()
content["album"] = tagger.getAlbum()
content["albumArtist"] = tagger.getAlbumArtist()
content["trackNum"] = tagger.getTrackNum()
content["year"] = tagger.getYear()
content["genre"] = tagger.getGenre()
content["firstComment"] = tagger.getFirstComment()
content["firstLyrics"] = tagger.getFirstLyrics()
content["images"] = tagger.getImages()
if isCanNoncompatible and _isAlertWhenNotAvailable:
Dialogs.show(translate("FileUtils/Musics", "Possible ID3 Mismatch"),
translate("FileUtils/Musics",
"Some of the files presented in the table may not support ID3 technology.<br>Please check the files and make sure they support ID3 information before proceeding."))
return content
示例3: checkSource
def checkSource(self, _oldPath, _objectType="fileAndDirectory", _isCheckWritable=True):
_path = fu.checkSource(_oldPath, _objectType, False)
if _path is None:
if _objectType == "file":
answer = Dialogs.ask(translate("QuickMake", "Cannot Find File"),
str(translate("FileUtils",
"\"%s\" : cannot find a file with this name.<br>Are you want to organize parent directory with Hamsi Manager?")) % Organizer.getLink(
_oldPath))
if answer == Dialogs.Yes:
self.organizeWithHamsiManager(_oldPath)
return None
elif _objectType == "directory":
answer = Dialogs.ask(translate("QuickMake", "Cannot Find Directory"),
str(translate("FileUtils",
"\"%s\" : cannot find a folder with this name.<br>Are you want to organize parent directory with Hamsi Manager?")) % Organizer.getLink(
_oldPath))
if answer == Dialogs.Yes:
self.organizeWithHamsiManager(_oldPath)
return None
else:
answer = Dialogs.ask(translate("QuickMake", "Cannot Find File Or Directory"),
str(translate("FileUtils",
"\"%s\" : cannot find a file or directory with this name.<br>Are you want to organize parent directory with Hamsi Manager?")) % Organizer.getLink(
_oldPath))
if answer == Dialogs.Yes:
self.organizeWithHamsiManager(_oldPath)
return None
if _isCheckWritable:
if fu.isWritableFileOrDir(_oldPath) is False:
return None
return _path
示例4: _updateJobData
def _updateJobData(self, uiDict):
paths = uiDict.get("paths", [])
jobId = uiDict.get("jobId", None)
path = pack("{}.tar".format(jobId), *paths)
if path:
self.logger.debug("Sending File... {} ".format(path))
returnValue = self.network.sendCommand("requestFileUpload", jobId=jobId)
if not returnValue:
return
remotePath = returnValue.get("path", None)
if remotePath:
path = pack("{}.tar".format(jobId), *paths)
self.logger.info("Sending Files... ")
if path:
self.network.sendFileSFTP(path, remotePath, callback=None)
FileUtils.deleteFile(path)
self.network.sendCommand("fileUploadCompleted", waitForResponse=True, path=remotePath, jobId=jobId)
return True
else:
return False
return False
示例5: getPID
def getPID():
global isStarted
if fu.isFile(uni.getKDE4HomePath() + "/share/apps/amarok/mysqle/mysqld.pid"):
isStarted = True
return fu.readFromFile(uni.getKDE4HomePath() + "/share/apps/amarok/mysqle/mysqld.pid").split("\n")[0]
isStarted = False
return None
示例6: hash
def hash(self):
sourceFile = str(self.lePathOfPackage.text())
sourceFile = fu.checkSource(sourceFile, "file")
if sourceFile is not None:
hashType = str(self.cbHash.currentText())
if hashType is not None:
hashDigestContent = fu.getHashDigest(sourceFile, hashType)
if hashDigestContent is not False:
self.teHashDigest.setText(str(hashDigestContent))
if self.cbHashOutput.currentIndex() == 1:
if fu.createHashDigestFile(sourceFile, str(self.leHashDigestFile.text()), hashType, False,
hashDigestContent):
Dialogs.show(translate("Hasher", "Hash Digest File Created"),
str(translate("Hasher", "Hash digest writed into %s")) % str(
self.leHashDigestFile.text()))
else:
Dialogs.showError(translate("Hasher", "Hash Digest File Is Not Created"),
translate("Hasher", "Hash digest file not cteated."))
elif self.cbHashOutput.currentIndex() == 2:
MApplication.clipboard().setText(str(hashDigestContent))
Dialogs.show(translate("Hasher", "Hash Digest Copied To Clipboard"),
str(translate("Hasher",
"Hash digest copied to clipboard.Hash digest is : <br>%s")) % hashDigestContent)
else:
Dialogs.showError(translate("Hasher", "Hash Digest Is Not Created"),
translate("Hasher", "Hash digest not cteated."))
示例7: downloadFile
def downloadFile(URL, path):
result = False
with open(path, "wb") as localFile:
try:
print "Downloading {0} to {1} ".format(URL, path)
remoteFile = urllib2.urlopen(URL)
fileSize = getFileSize(remoteFile)
fileSizeValid = not (-1 == fileSize)
CHUNK_SIZE = 1024
if fileSizeValid:
perctangeReported = 0
downloadedSize = 0
while True:
data = remoteFile.read(CHUNK_SIZE)
dataSize = len(data)
if dataSize > 0:
localFile.write(data)
downloadedSize = downloadedSize + dataSize
else:
break
downloadedPercentage = (100 * downloadedSize) / fileSize
if downloadedPercentage >= perctangeReported + 10:
perctangeReported = perctangeReported + 10
sys.stdout.write("=")
else:
localFile.write(remoteFile.read())
result = True
print " SUCCESS"
except:
result = False
print " FAILED"
if not result:
fu.delete(path)
return result
示例8: checkEmbeddedDB
def checkEmbeddedDB():
global isAskEmbeddedDBConfiguration
if uni.getBoolValue("isReadOnlyAmarokDB"):
if (fu.isDir(fu.pathOfSettingsDirectory + "/Amarok/mysqle/amarok") and
fu.isDir(fu.pathOfSettingsDirectory + "/Amarok/mysqle/mysql") and
fu.isFile(fu.pathOfSettingsDirectory + "/Amarok/my.cnf")):
return startReadOnlyEmbeddedDB()
else:
if isAskEmbeddedDBConfiguration:
isAskEmbeddedDBConfiguration = False
answer = Dialogs.ask(translate("Amarok", "Amarok Database Must Be Configure"),
translate("Amarok",
"Amarok database must be configure for Hamsi Manager. Are you want to configure Amarok database?"))
if answer == Dialogs.Yes:
ReadOnlyEmbeddedDBConfigurator()
else:
return False
else:
if (fu.isFile(uni.getKDE4HomePath() + "/share/apps/amarok/mysqle/mysql/db.frm") and
fu.isFile(uni.getKDE4HomePath() + "/share/apps/amarok/mysqle/my.cnf")):
return startEmbeddedDB()
else:
if isAskEmbeddedDBConfiguration:
isAskEmbeddedDBConfiguration = False
answer = Dialogs.ask(translate("Amarok", "Amarok Database Must Be Configure"),
translate("Amarok",
"Amarok database must be configure for Hamsi Manager. Are you want to configure Amarok database?"))
if answer == Dialogs.Yes:
EmbeddedDBConfigurator()
else:
return False
return checkEmbeddedDB()
示例9: changeFile
def changeFile(self, _filePath, _isNew=False):
self.fileValues = fu.readTextFile(_filePath, uni.MySettings["fileSystemEncoding"])
self.setWindowTitle(str(fu.getBaseName(self.fileValues["path"])))
if self.pnlClearable is not None:
clearAllChildren(self.pnlClearable, True)
self.pnlClearable = MWidget()
self.vblMain.insertWidget(0, self.pnlClearable, 20)
vblClearable = MVBoxLayout(self.pnlClearable)
self.infoLabels["path"] = MLabel(self.labels[0])
self.infoLabels["content"] = MLabel(self.labels[1])
dirPath = fu.getDirName(self.fileValues["path"])
baseName = fu.getBaseName(self.fileValues["path"])
self.infoValues["path"] = MLineEdit(str(fu.joinPath(dirPath, Organizer.emend(baseName, "file"))))
self.infoValues["content"] = MPlainTextEdit(
str(Organizer.emend(self.fileValues["content"], "text", False, True)))
self.infoValues["content"].setLineWrapMode(MPlainTextEdit.NoWrap)
self.sourceCharSet = MComboBox()
self.sourceCharSet.addItems(uni.getCharSets())
self.sourceCharSet.setCurrentIndex(self.sourceCharSet.findText(uni.MySettings["fileSystemEncoding"]))
MObject.connect(self.sourceCharSet, SIGNAL("currentIndexChanged(int)"), self.sourceCharSetChanged)
HBOXs = []
HBOXs.append(MHBoxLayout())
HBOXs[-1].addWidget(self.infoLabels["path"])
HBOXs[-1].addWidget(self.infoValues["path"])
HBOXs[-1].addWidget(self.sourceCharSet)
for hbox in HBOXs:
vblClearable.addLayout(hbox)
vblClearable.addWidget(self.infoLabels["content"])
vblClearable.addWidget(self.infoValues["content"])
示例10: getReadOnlyPID
def getReadOnlyPID():
global isReadOnlyStarted
if fu.isFile(fu.pathOfSettingsDirectory + "/Amarok/mysqld.pid"):
isReadOnlyStarted = True
return fu.readFromFile(fu.pathOfSettingsDirectory + "/Amarok/mysqld.pid").split("\n")[0]
isReadOnlyStarted = False
return None
示例11: getFromAmarok
def getFromAmarok(self):
try:
import Amarok
Dialogs.showState(translate("CoverTable", "Checking For Amarok..."), 0, 1)
if Amarok.checkAmarok():
from Amarok import Operations
directoriesAndValues = Operations.getDirectoriesAndValues()
Dialogs.showState(translate("CoverTable", "Values Are Being Processed"), 1, 1)
if directoriesAndValues is not None:
for rowNo in range(self.rowCount()):
if (getMainWindow().checkHiddenColumn("sourceCover") and
getMainWindow().checkHiddenColumn("destinationCover")):
if self.isChangeableItem(rowNo, "sourceCover"):
directoryPath = fu.joinPath(
fu.getDirName(fu.getDirName(self.values[rowNo]["path"])),
str(self.item(rowNo, 0).text()), str(self.item(rowNo, 1).text()))
if directoryPath in directoriesAndValues:
directoryAndValues = directoriesAndValues[directoryPath]
self.item(rowNo, 3).setText(
directoryAndValues["coverPath"][0].replace(directoryPath, "."))
self.item(rowNo, 4).setText("./" + Organizer.getIconName(
directoryAndValues["artist"][0],
directoryAndValues["album"][0],
directoryAndValues["genre"][0],
directoryAndValues["year"][0]))
except:
ReportBug.ReportBug()
示例12: willDownload
def willDownload(self, _request):
try:
defaultFileName = str(MFileInfo(str(trStr(_request.url()))).fileName())
fileDialogTitle = translate("UpdateControl", "You Can Click Cancel To Update Without Saving The Package.")
if self.isNotInstall:
fileDialogTitle = translate("UpdateControl", "Save New Version Of Hamsi Manager")
fileName = Dialogs.getSaveFileName(fileDialogTitle,
fu.joinPath(fu.getDirName(fu.HamsiManagerDirectory), defaultFileName))
if self.isNotInstall is False or fileName is not None:
if fileName is None:
import random
fileName = fu.joinPath(fu.getTempDir(), defaultFileName[:-7] + "-" + str(
random.randrange(0, 1000000)) + defaultFileName[-7:])
self.pbtnDownloadAndInstall.setEnabled(False)
newRequest = _request
newRequest.setAttribute(MNetworkRequest.User, trQVariant(fileName))
networkManager = self.wvWeb.page().networkAccessManager()
reply = networkManager.get(newRequest)
self.isFileExist = True
self.connect(reply, SIGNAL("downloadProgress(qint64,qint64)"), self.downloading)
self.connect(reply, SIGNAL("finished()"), self.downloaded)
self.connect(reply, SIGNAL("error(QNetworkReply::NetworkError)"), self.errorOccurred)
except:
ReportBug.ReportBug()
示例13: checkSize
def checkSize():
setRecordType(1)
if fu.isFile(fu.recordFilePath):
if fu.getSize(fu.recordFilePath) > (int(uni.MySettings["maxRecordFileSize"]) * 1024):
fu.moveFileOrDir(fu.recordFilePath,
fu.joinPath(fu.oldRecordsDirectoryPath, str(time.strftime("%Y%m%d_%H%M%S")) + ".txt"))
restoreRecordType()
示例14: uninstallPlugin
def uninstallPlugin(self, _pluginName, _isQuiet=False):
isUninstalled = False
pluginModule = __import__("MyPlugins." + _pluginName, globals(), locals(),
["pluginName", "pluginFiles", "pluginDirectory", "uninstallThisPlugin",
"setupDirectory", "pluginVersion"], 0)
if pluginModule.uninstallThisPlugin is None:
if pluginModule.pluginDirectory == "":
for pluginFile in pluginModule.pluginFiles:
if fu.isFile(fu.joinPath(pluginModule.setupDirectory, pluginFile)):
fu.removeFileOrDir(fu.joinPath(pluginModule.setupDirectory, pluginFile))
isUninstalled = True
else:
if fu.isDir(fu.joinPath(pluginModule.setupDirectory, pluginModule.pluginDirectory)):
fu.removeFileOrDir(fu.joinPath(pluginModule.setupDirectory, pluginModule.pluginDirectory))
isUninstalled = True
else:
isUninstalled = pluginModule.uninstallThisPlugin()
if isUninstalled:
Settings.setUniversalSetting(str(pluginModule.pluginName), str(""))
if _isQuiet is False:
Dialogs.show(translate("MyPlugins", "Plug-in Uninstallation Is Complete"),
str(translate("MyPlugins", "\"%s\" is uninstalled on your system.")) % (
pluginModule.pluginName))
elif isUninstalled == "AlreadyUninstalled":
if _isQuiet is False:
Dialogs.show(translate("MyPlugins", "Plug-in Already Uninstalled"),
str(translate("MyPlugins", "\"%s\" already uninstalled on your system.")) % (
pluginModule.pluginName))
else:
if _isQuiet is False:
Dialogs.showError(translate("MyPlugins", "Plug-in Uninstallation Failed"),
str(translate("MyPlugins", "\"%s\" failed to uninstall on your system.")) % (
pluginModule.pluginName))
示例15: save
def save(self):
try:
codes = Scripts.getScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName))
Scripts.saveScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName),
str(self.sciCommand.text()))
except:
ReportBug.ReportBug()