本文整理汇总了Python中file.File类的典型用法代码示例。如果您正苦于以下问题:Python File类的具体用法?Python File怎么用?Python File使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了File类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save_data_2_file
def save_data_2_file(self, blog_list, file_name='blog_info',):
file = File()
file_write_file = file.opne_file(file_name, "w")
for blog in blog_list:
content = blog['blog_name'] + '------' + blog['blog_url'] + '\n'
file.save_file(file_write_file, file_name, content)
file_write_file.close()
示例2: added
def added(self, path, client):
path = path.replace("\\", "/")
file_extension_pattern=self.path_to_watch+"/chunks"
if (re.search("Thumbs.db", path) == None):
# Checks if folder is chunks, only if it isn't it will send modifications
if (re.search(file_extension_pattern,path) == None):
# Prints message of file added
print_message("Added: " + path)
if (os.path.isfile(path)):
# Creates file information
f = File(path, client)
f.generate_file_id()
f.get_salt()
file_size = f.get_file_size()
# Gets relative_path location
relative_path = path.split(self.path_to_watch)[1].replace("\\", "/")
modification_date = f.get_modification_date().replace(" ", "T").split(".")[0] +"Z"
# Sends request to server with information about the new file
url = self.api+'files/create.php'
values = {'apikey': '12',
'path': relative_path,
'user': client.get_email(),
'modification': f.get_file_id(),
'dateModified': modification_date,
'size': str(int(file_size))
}
response = json_request(url, values)
if (response['result'] == 'notEnoughSpace'):
print_message("Not enough space. Space left to use " + str(response['spaceLeft']))
window = Tkinter.Tk()
window.wm_withdraw()
tkMessageBox.showerror(title="Budibox", message="Not enough space! Space left to use " + str(response['spaceLeft']) + "bytes !")
return
if (response['result'] != 'ok'):
print_message("Error sending information created about file " + path)
return
print_message("Created file " + path + " successfully")
url = self.api+'files/getId.php'
values = {'apikey': '12',
'path': relative_path,
'user': client.get_email(),
}
response = json_request(url, values)
if (response['result'] != 'ok'):
print_message("Error getting fileId of " + path)
return
print_message("Get fileId of " + path + "successfully")
# Send information about chunks to server
db_file_id = response['id']
f.generate_chunks(db_file_id)
示例3: _test_naming_util
def _test_naming_util(my):
#my.clear_naming()
naming_util = NamingUtil()
# these should evaluate to be the same
file_naming_expr1 = ['{$PROJECT}__{context[0]}__hi_{$BASEFILE}.{$EXT}','{project.code}__{context[0]}__hi_{basefile}.{ext}']
dir_naming_expr2 = ['{$PROJECT}/{context[1]}/somedir/{@GET(.name_first)}','{project.code}/{snapshot.context[1]}/somedir/{sobject.name_first}']
process= 'light'
context = 'light/special'
type = 'ma'
version = 2
virtual_snapshot = Snapshot.create_new()
virtual_snapshot_xml = '<snapshot process=\'%s\'><file type=\'%s\'/></snapshot>' % (process, type)
virtual_snapshot.set_value("snapshot", virtual_snapshot_xml)
virtual_snapshot.set_value("process", process)
virtual_snapshot.set_value("context", context)
virtual_snapshot.set_value("snapshot_type", 'file')
virtual_snapshot.set_sobject(my.person)
virtual_snapshot.set_value("version", version)
file_name = "abc.txt"
file_obj = File(File.SEARCH_TYPE)
file_obj.set_value("file_name", file_name)
for naming_expr in file_naming_expr1:
file_name = naming_util.naming_to_file(naming_expr, my.person, virtual_snapshot, file=file_obj, file_type="main")
my.assertEquals(file_name,'unittest__light__hi_abc.txt')
for naming_expr in dir_naming_expr2:
dir_name = naming_util.naming_to_dir(naming_expr, my.person, virtual_snapshot, file=file_obj, file_type="main")
my.assertEquals(dir_name,'unittest/special/somedir/Philip')
示例4: TestFile
class TestFile(unittest.TestCase):
def setUp(self):
self.file = File('testfilename',
123,
234,
True)
@mock.patch('file.requests')
def test_getFileSet(self,
mock_requests):
test_data = {'next': None,
'results': [{'filename': 'file1'},
{'filename': 'file2'},
{'filename': 'file3'}],
}
mock_request = mock.MagicMock()
mock_request.json.return_value = test_data
mock_requests.get.return_value = mock_request
expectedSet = set(['file1',
'file2',
'file3',
])
self.assertEquals(expectedSet, self.file.getFileSet(1))
示例5: __on_export_image
def __on_export_image(self, _event):
dlgFile = wx.FileDialog(
self,
"Export image to file",
self.settings.dirExport,
self.filename,
File.get_type_filters(File.Types.IMAGE),
wx.SAVE | wx.OVERWRITE_PROMPT,
)
dlgFile.SetFilterIndex(File.ImageType.PNG)
if dlgFile.ShowModal() == wx.ID_OK:
dlgImg = DialogImageSize(self, self.settings)
if dlgImg.ShowModal() != wx.ID_OK:
dlgFile.Destroy()
return
self.status.set_general("Exporting...")
fileName = dlgFile.GetFilename()
dirName = dlgFile.GetDirectory()
self.settings.dirExport = dirName
fileName = extension_add(fileName, dlgFile.GetFilterIndex(), File.Types.IMAGE)
fullName = os.path.join(dirName, fileName)
exportType = dlgFile.GetFilterIndex()
export_image(fullName, exportType, self.graph.get_figure(), self.settings)
self.status.set_general("Finished")
dlgFile.Destroy()
示例6: updateFileRecords
def updateFileRecords(self, path, localFileSet, remoteFileSet):
pathid = None
for localFile in localFileSet:
if localFile not in remoteFileSet:
try:
if not pathid:
pathid = self.getOrCreateRemotePath(path)
log.debug("Attempting to add %s" % (localFile,))
fullPath = stripUnicode(localFile, path=path)
try:
fullPath = makeFileStreamable(fullPath,
appendSuffix=True,
removeOriginal=True,
dryRun=False)
except Exception, e:
log.error(e)
log.error("Something bad happened. Attempting to continue")
if os.path.exists(fullPath):
newFile = File(os.path.basename(fullPath),
pathid,
os.path.getsize(fullPath),
True,
)
newFile.post()
except Exception, e:
log.error(e)
continue
示例7: getProjectfileTimestamps
def getProjectfileTimestamps(name):
projectfile = File.projectfileFromName(name)
timestamps = {}
timestamps["creation"] = File.fileCreationTimestamp(projectfile)
timestamps["modification"] = File.fileModificationTimestamp(projectfile)
return timestamps
示例8: get_rotation
def get_rotation(self, path_to_file):
metadata = {}
with exiftool.ExifTool() as et:
metadata = et.get_metadata(path_to_file)
f = File(path_to_file)
tag = f.rotation_tag()
if tag not in metadata:
return 0
return int(metadata[tag])
示例9: __arguments
def __arguments():
parser = argparse.ArgumentParser(prog="rtlsdr_scan.py",
description='''
Scan a range of frequencies and
save the results to a file''')
parser.add_argument("-s", "--start", help="Start frequency (MHz)",
type=int)
parser.add_argument("-e", "--end", help="End frequency (MHz)", type=int)
parser.add_argument("-w", "--sweeps", help="Number of sweeps", type=int,
default=1)
parser.add_argument("-p", "--delay", help="Delay between sweeps (s)",
type=int, default=0)
parser.add_argument("-g", "--gain", help="Gain (dB)", type=float, default=0)
parser.add_argument("-d", "--dwell", help="Dwell time (seconds)",
type=float, default=0.1)
parser.add_argument("-f", "--fft", help="FFT bins", type=int, default=1024)
parser.add_argument("-l", "--lo", help="Local oscillator offset",
type=int, default=0)
parser.add_argument("-c", "--conf", help="Load a config file",
default=None)
group = parser.add_mutually_exclusive_group()
group.add_argument("-i", "--index", help="Device index (from 0)", type=int,
default=0)
group.add_argument("-r", "--remote", help="Server IP and port", type=str)
types = File.get_type_pretty(File.Types.SAVE)
types += File.get_type_pretty(File.Types.PLOT)
help = 'Output file (' + types + ')'
parser.add_argument("file", help=help, nargs='?')
args = parser.parse_args()
error = None
isGui = True
if args.start is not None or args.end is not None:
if args.start is not None:
if args.end is not None:
if args.file is not None:
isGui = False
else:
error = "No filename specified"
else:
error = "No end frequency specified"
else:
error = "No start frequency specified"
elif args.file is not None:
args.dirname, args.filename = os.path.split(args.file)
if error is not None:
print "Error: {}".format(error)
parser.exit(1)
return isGui, (args)
示例10: consume
def consume(lock, graphs, done, critical):
while done.empty():
try:
g = graphs.get(block=True, timeout=5)
d = DalGraph(graph=g, logger=LOGGER)
if d.critical_aprox():
f = File(DIRECTORY, G=g, logger=LOGGER)
fp = f.save()
if fp is not None:
critical.put(fp)
except Empty:
#print("Empty")
pass
return
示例11: __init__
def __init__(self):
self.config = Config()
self.config.load('config.yaml')
self.cellfont = pygame.font.SysFont('arial',10)
self.file = File()
self.fpsClock = pygame.time.Clock()
self.load()
示例12: __init__
class IMDBScraper:
def __init__(self, file_name):
self.open_file = File(file_name)
self.open_file.skipToData()
def next(self):
actor = Actor("init", "actor")
for line in self.open_file.next():
if (line.containsActorName()):
yield actor
actor, film = line.getActorAndFilm()
actor.addFilm(film)
else:
film = line.getFilm()
if not film is None:
actor.addFilm(film)
示例13: addToCollection
def addToCollection(query):
from paths import add_to_collection
from src.file import File
vSourceId, vSourceFile, sourceType = _decodedUrl(query)
vSourceFile = File.fromFullpath(vSourceFile)
add_to_collection.add(vSourceId, vSourceFile, sourceType)
示例14: playVideoSource
def playVideoSource(query):
from file import File
from paths import play_video_source
videoId, sourceId, collectionFile = _decodeQuery(query)
collectionFile = File.fromQuery(collectionFile)
play_video_source.play(videoId, sourceId, collectionFile)
示例15: __init__
class FileMenuInit:
def __init__(self, builder):
self.builder = builder
self.top_level = builder.get_object("top_level")
self.fo = None
self.rc = RcFile()
open_menu_item = self.builder.get_object("open_menu_item")
open_menu_item.connect("activate", self.on_open_menu_item_activate)
quit_menu_item = self.builder.get_object("quit_menu_item")
quit_menu_item.connect("activate", self.on_quit_menu_item_activate)
open_toolbar_button = self.builder.get_object("open_toolbar_button")
open_toolbar_button.connect("clicked", self.on_open_menu_item_activate)
self.fo = File(self.builder)
def on_open_menu_item_activate(self, menuitem, data=None):
file, dir = self.fo.load_file(self.rc.rc_hash["OPEN_DIR"])
if file != None:
self.top_level.set_title(os.path.basename(file))
if dir != None:
self.rc.UpdateRcValue("OPEN_DIR", dir)
def on_quit_menu_item_activate(self, menuitem, data=None):
RcFile().WriteRcFile()
gtk.main_quit()