How to use make_dirs_for_file method in Playwright Python

Best Python code snippet using playwright-python

fsutil.py

Source:fsutil.py Github

copy

Full Screen

...137 """138 assert_file(path)139 if not overwrite:140 assert_not_exists(dest)141 make_dirs_for_file(dest)142 shutil.copy2(path, dest, **kwargs)143def create_dir(path, overwrite=False):144 """145 Create directory at the given path.146 If overwrite is not allowed and path exists, an OSError is raised.147 """148 if not overwrite:149 assert_not_exists(path)150 make_dirs(path)151def create_file(path, content='', overwrite=False):152 """153 Create file with the specified content at the given path.154 If overwrite is not allowed and path exists, an OSError is raised.155 """156 if not overwrite:157 assert_not_exists(path)158 write_file(path, content)159def create_zip_file(160 path, content_paths, overwrite=True, compression=zipfile.ZIP_DEFLATED161):162 """163 Create zip file at path compressing directories/files listed in content_paths.164 If overwrite is allowed and dest zip already exists, it will be overwritten.165 """166 assert_not_dir(path)167 if not overwrite:168 assert_not_exists(path)169 make_dirs_for_file(path)170 def _write_content_to_zip_file(file, path, basedir=''):171 assert_exists(path)172 if is_file(path):173 filename = get_filename(path)174 filepath = join_path(basedir, filename)175 file.write(path, filepath)176 elif is_dir(path):177 for item_name in os.listdir(path):178 item_path = join_path(path, item_name)179 if is_dir(item_path):180 basedir = join_path(basedir, item_name)181 _write_content_to_zip_file(file, item_path, basedir)182 with zipfile.ZipFile(path, 'w', compression) as file:183 for content_path in content_paths:184 _write_content_to_zip_file(file, content_path)185def delete_dir(path):186 """187 Alias for remove_dir.188 """189 removed = remove_dir(path)190 return removed191def delete_dir_content(path):192 """193 Alias for remove_dir_content.194 """195 remove_dir_content(path)196def delete_dirs(*paths):197 """198 Alias for remove_dirs.199 """200 remove_dirs(*paths)201def delete_file(path):202 """203 Alias for remove_file.204 """205 removed = remove_file(path)206 return removed207def delete_files(*paths):208 """209 Alias for remove_files.210 """211 remove_files(*paths)212def download_file(url, dirpath, filename=None, chunk_size=8192, **kwargs):213 """214 Download a file from url to dirpath.215 If filename is provided, the file will be named using filename.216 It is possible to pass extra request options (eg. for authentication) using **kwargs.217 """218 # https://stackoverflow.com/a/16696317/2096218219 filename = filename or get_filename(url) or 'download'220 filepath = join_path(dirpath, filename)221 make_dirs_for_file(filepath)222 kwargs['stream'] = True223 with requests.get(url, **kwargs) as response:224 response.raise_for_status()225 with open(filepath, 'wb') as file:226 for chunk in response.iter_content(chunk_size=chunk_size):227 if chunk:228 file.write(chunk)229 return filepath230def exists(path):231 """232 Check if a directory of a file exists at the given path.233 """234 return os.path.exists(path)235def extract_zip_file(path, dest, autodelete=False, content_paths=None):236 """237 Extract zip file at path to dest path.238 If autodelete, the archive will be deleted after extraction.239 If content_paths list is defined, only listed items will be extracted, otherwise all.240 """241 assert_file(path)242 make_dirs(dest)243 with zipfile.ZipFile(path, 'r') as file:244 file.extractall(dest, members=content_paths)245 if autodelete:246 remove_file(path)247def _filter_paths(basepath, relpaths, predicate=None):248 """249 Filter paths relative to basepath according to the optional predicate function.250 If predicate is defined, paths are filtered using it, otherwise all paths will be listed.251 """252 paths = []253 for relpath in relpaths:254 abspath = os.path.join(basepath, relpath)255 if predicate is None or predicate(abspath):256 paths.append(abspath)257 paths.sort()258 return paths259def get_dir_creation_date(path):260 """261 Get the directory creation date.262 """263 assert_dir(path)264 creation_timestamp = os.path.getctime(path)265 creation_date = dt.datetime.fromtimestamp(creation_timestamp)266 return creation_date267def get_dir_creation_date_formatted(path, format='%Y-%m-%d %H:%M:%S'):268 """269 Get the directory creation date formatted using the given format.270 """271 date = get_dir_creation_date(path)272 return date.strftime(format)273def get_dir_last_modified_date(path):274 """275 Get the directory last modification date.276 """277 assert_dir(path)278 last_modified_timestamp = os.path.getmtime(path)279 for basepath, dirnames, filenames in os.walk(path):280 for dirname in dirnames:281 dirpath = os.path.join(basepath, dirname)282 last_modified_timestamp = max(283 last_modified_timestamp, os.path.getmtime(dirpath)284 )285 for filename in filenames:286 filepath = os.path.join(basepath, filename)287 last_modified_timestamp = max(288 last_modified_timestamp, os.path.getmtime(filepath)289 )290 last_modified_date = dt.datetime.fromtimestamp(last_modified_timestamp)291 return last_modified_date292def get_dir_last_modified_date_formatted(path, format='%Y-%m-%d %H:%M:%S'):293 """294 Get the directory last modification date formatted using the given format.295 """296 date = get_dir_last_modified_date(path)297 return date.strftime(format)298def get_dir_size(path):299 """300 Get the directory size in bytes.301 """302 assert_dir(path)303 size = 0304 for basepath, _, filenames in os.walk(path):305 for filename in filenames:306 filepath = os.path.join(basepath, filename)307 if not os.path.islink(filepath):308 size += get_file_size(filepath)309 return size310def get_dir_size_formatted(path):311 """312 Get the directory size formatted using the right unit suffix.313 """314 size = get_dir_size(path)315 size_formatted = convert_size_bytes_to_string(size)316 return size_formatted317def get_file_basename(path):318 """319 Get the file basename from the given path/url.320 """321 basename, _ = split_filename(path)322 return basename323def get_file_creation_date(path):324 """325 Get the file creation date.326 """327 assert_file(path)328 creation_timestamp = os.path.getctime(path)329 creation_date = dt.datetime.fromtimestamp(creation_timestamp)330 return creation_date331def get_file_creation_date_formatted(path, format='%Y-%m-%d %H:%M:%S'):332 """333 Get the file creation date formatted using the given format.334 """335 date = get_file_creation_date(path)336 return date.strftime(format)337def get_file_extension(path):338 """339 Get the file extension from the given path/url.340 """341 _, extension = split_filename(path)342 return extension343def get_file_hash(path, func='md5'):344 """345 Get the hash of the file at the gived path using346 the specified algorithm function (md5 by default).347 """348 assert_file(path)349 hash = hashlib.new(func)350 with open(path, 'rb') as file:351 for chunk in iter(lambda: file.read(4096), b''):352 hash.update(chunk)353 hash_hex = hash.hexdigest()354 return hash_hex355def get_file_last_modified_date(path):356 """357 Get the file last modification date.358 """359 assert_file(path)360 last_modified_timestamp = os.path.getmtime(path)361 last_modified_date = dt.datetime.fromtimestamp(last_modified_timestamp)362 return last_modified_date363def get_file_last_modified_date_formatted(path, format='%Y-%m-%d %H:%M:%S'):364 """365 Get the file last modification date formatted using the given format.366 """367 date = get_file_last_modified_date(path)368 return date.strftime(format)369def get_file_size(path):370 """371 Get the directory size in bytes.372 """373 assert_file(path)374 # size = os.stat(path).st_size375 size = os.path.getsize(path)376 return size377def get_file_size_formatted(path):378 """379 Get the directory size formatted using the right unit suffix.380 """381 size = get_file_size(path)382 size_formatted = convert_size_bytes_to_string(size)383 return size_formatted384def get_filename(path):385 """386 Get the filename from the given path/url.387 """388 filepath = urlsplit(path).path389 filename = os.path.basename(filepath)390 return filename391def get_parent_dir(path, levels=1):392 """393 Get the parent directory for the given path going up N levels.394 """395 return join_path(path, *([os.pardir] * max(1, levels)))396def is_dir(path):397 """398 Determine whether the specified path represents an existing directory.399 """400 return os.path.isdir(path)401def is_empty(path):402 """403 Determine whether the specified path represents an empty directory or an empty file.404 """405 assert_exists(path)406 if is_dir(path):407 return is_empty_dir(path)408 return is_empty_file(path)409def is_empty_dir(path):410 """411 Determine whether the specified path represents an empty directory.412 """413 assert_dir(path)414 return len(os.listdir(path)) == 0415def is_empty_file(path):416 """417 Determine whether the specified path represents an empty file.418 """419 return get_file_size(path) == 0420def is_file(path):421 """422 Determine whether the specified path represents an existing file.423 """424 return os.path.isfile(path)425def join_filename(basename, extension):426 """427 Create a filename joining the file basename and the extension.428 """429 basename = basename.rstrip('.').strip()430 extension = extension.replace('.', '').strip()431 filename = '{}.{}'.format(basename, extension)432 return filename433def join_filepath(dirpath, filename):434 """435 Create a filepath joining the directory path and the filename.436 """437 return join_path(dirpath, filename)438def join_path(path, *paths):439 """440 Create a path joining path and paths.441 If path is __file__ (or a .py file), the resulting path will be relative442 to the directory path of the module in which it's used.443 """444 basepath = path445 if get_file_extension(path) in ['py', 'pyc', 'pyo']:446 basepath = os.path.dirname(os.path.realpath(path))447 paths = [path.lstrip(os.sep) for path in paths]448 return os.path.normpath(os.path.join(basepath, *paths))449def list_dirs(path):450 """451 List all directories contained at the given directory path.452 """453 return _filter_paths(path, os.listdir(path), predicate=is_dir)454def list_files(path):455 """456 List all files contained at the given directory path.457 """458 return _filter_paths(path, os.listdir(path), predicate=is_file)459def _make_dirs_py2(path):460 # https://stackoverflow.com/questions/12517451/automatically-creating-directories-with-file-output461 try:462 os.makedirs(path)463 except OSError as e:464 # Guard against race condition465 if e.errno != errno.EEXIST:466 raise e467def make_dirs(path):468 """469 Create the directories needed to ensure that the given path exists.470 If a file already exists at the given path an OSError is raised.471 """472 if is_dir(path):473 return474 assert_not_file(path)475 if PY2:476 _make_dirs_py2(path)477 return478 os.makedirs(path, exist_ok=True)479def make_dirs_for_file(path):480 """481 Create the directories needed to ensure that the given path exists.482 If a directory already exists at the given path an OSError is raised.483 """484 if is_file(path):485 return486 assert_not_dir(path)487 dirpath, _ = split_filepath(path)488 make_dirs(dirpath)489def move_dir(path, dest, overwrite=False, **kwargs):490 """491 Move an existing dir from path to dest directory.492 If overwrite is not allowed and dest path exists, an OSError is raised.493 More informations about kwargs supported options here:494 https://docs.python.org/3/library/shutil.html#shutil.move495 """496 assert_dir(path)497 assert_not_file(dest)498 if not overwrite:499 assert_not_exists(dest)500 make_dirs(dest)501 shutil.move(path, dest, **kwargs)502def move_file(path, dest, overwrite=False, **kwargs):503 """504 Move an existing file from path to dest directory.505 If overwrite is not allowed and dest path exists, an OSError is raised.506 More informations about kwargs supported options here:507 https://docs.python.org/3/library/shutil.html#shutil.move508 """509 assert_file(path)510 assert_not_file(dest)511 dest = os.path.join(dest, get_filename(path))512 assert_not_dir(dest)513 if not overwrite:514 assert_not_exists(dest)515 make_dirs_for_file(dest)516 shutil.move(path, dest, **kwargs)517def read_file(path, encoding='utf-8'):518 """519 Read the content of the file at the given path using the specified encoding.520 """521 assert_file(path)522 content = ''523 options = {} if PY2 else {'encoding': encoding}524 with open(path, 'r', **options) as file:525 content = file.read()526 return content527def read_file_from_url(url, **kwargs):528 """529 Read the content of the file at the given url.530 """531 response = requests.get(url, **kwargs)532 response.raise_for_status()533 content = response.text534 return content535def read_file_lines(path, strip_white=True, skip_empty=True, encoding='utf-8'):536 """537 Read file content lines according to the given options.538 """539 content = read_file(path, encoding)540 lines = content.splitlines()541 if strip_white:542 lines = [line.strip() for line in lines]543 if skip_empty:544 lines = [line for line in lines if line]545 return lines546def remove_dir(path, **kwargs):547 """548 Remove a directory at the given path and all its content.549 If the directory is removed with success returns True, otherwise False.550 More informations about kwargs supported options here:551 https://docs.python.org/3/library/shutil.html#shutil.rmtree552 """553 if not exists(path):554 return False555 assert_dir(path)556 shutil.rmtree(path, **kwargs)557 return not exists(path)558def remove_dir_content(path):559 """560 Removes all directory content (both sub-directories and files).561 """562 assert_dir(path)563 remove_dirs(*list_dirs(path))564 remove_files(*list_files(path))565def remove_dirs(*paths):566 """567 Remove multiple directories at the given paths and all their content.568 """569 for path in paths:570 remove_dir(path)571def remove_file(path):572 """573 Remove a file at the given path.574 If the file is removed with success returns True, otherwise False.575 """576 if not exists(path):577 return False578 assert_file(path)579 os.remove(path)580 return not exists(path)581def remove_files(*paths):582 """583 Remove multiple files at the given paths.584 """585 for path in paths:586 remove_file(path)587def rename_dir(path, name):588 """589 Rename a directory with the given name.590 If a directory or a file with the given name already exists, an OSError is raised.591 """592 assert_dir(path)593 comps = list(os.path.split(path))594 comps[-1] = name595 dest = os.path.join(*comps)596 assert_not_exists(dest)597 os.rename(path, dest)598def rename_file(path, name):599 """600 Rename a file with the given name.601 If a directory or a file with the given name already exists, an OSError is raised.602 """603 assert_file(path)604 dirpath, filename = split_filepath(path)605 dest = join_filepath(dirpath, name)606 assert_not_exists(dest)607 os.rename(path, dest)608def rename_file_basename(path, basename):609 """610 Rename a file basename with the given basename.611 """612 extension = get_file_extension(path)613 filename = join_filename(basename, extension)614 rename_file(path, filename)615def rename_file_extension(path, extension):616 """617 Rename a file extension with the given extension.618 """619 basename = get_file_basename(path)620 filename = join_filename(basename, extension)621 rename_file(path, filename)622def _search_paths(path, pattern):623 """624 Search all paths relative to path matching the given pattern.625 """626 assert_dir(path)627 pathname = os.path.join(path, pattern)628 options = {} if PY2 else {'recursive': True}629 paths = glob.glob(pathname, **options)630 return paths631def search_dirs(path, pattern):632 """633 Search for directories at path matching the given pattern.634 """635 return _filter_paths(path, _search_paths(path, pattern), predicate=is_dir)636def search_files(path, pattern):637 """638 Search for files at path matching the given pattern.639 """640 return _filter_paths(path, _search_paths(path, pattern), predicate=is_file)641def split_filename(path):642 """643 Split a filename and returns its basename and extension.644 """645 filename = get_filename(path)646 basename, extension = os.path.splitext(filename)647 extension = extension.replace('.', '').strip()648 return (basename, extension)649def split_filepath(path):650 """651 Split a filepath and returns its directory-path and filename.652 """653 dirpath = os.path.dirname(path)654 filename = get_filename(path)655 return (dirpath, filename)656def split_path(path):657 """658 Split a path and returns its path-names.659 """660 head, tail = os.path.split(path)661 names = head.split(os.sep) + [tail]662 names = list(filter(None, names))663 return names664def write_file(path, content, append=False, encoding='utf-8'):665 """666 Write file with the specified content at the given path.667 """668 make_dirs_for_file(path)669 mode = 'a' if append else 'w'670 options = {} if PY2 else {'encoding': encoding}671 with open(path, mode, **options) as file:...

Full Screen

Full Screen

GA_utils.py

Source:GA_utils.py Github

copy

Full Screen

...3import fnmatch4from json import load, dump5import pandas as pd6from Opticharge.settings import BASE_DIR7def make_dirs_for_file(path):8 '''make dir for files'''9 try:10 os.makedirs(os.path.dirname(path))11 except OSError:12 pass13def guess_path_type(path):14 '''guess what type of file'''15 if os.path.isfile(path):16 return 'File'17 if os.path.isdir(path):18 return 'Directory'19 if os.path.islink(path):20 return 'Symbolic Link'21 if os.path.ismount(path):22 return 'Mount Point'23 return 'Path'24def exist(path, overwrite=False, display_info=True):25 if os.path.exists(path):26 if overwrite:27 if display_info:28 print(f'{guess_path_type(path)}: {path} exists. Overwrite.')29 os.remove(path)30 return False31 if display_info:32 print(f'{guess_path_type(path)}: {path} exists.')33 return True34 if display_info:35 print(f'{guess_path_type(path)}: {path} does not exist.')36 return False37def load_instance(json_file):38 if exist(path=json_file, overwrite=False, display_info=True):39 with io.open(json_file, 'rt', newline='') as file_object:40 return load(file_object)41 return None42def calculate_distance(customer1, customer2):43 return ((customer1['coordinates']['x'] - customer2['coordinates']['x'])**2 + \44 (customer1['coordinates']['y'] - customer2['coordinates']['y'])**2)**0.545def text2jsonCust(customize=False):46 text_data_dir = os.path.join(BASE_DIR, 'dataC', 'text_customizeC' if customize else 'text')47 json_data_dir = os.path.join(BASE_DIR, 'dataC', 'json_customizeC' if customize else 'json')48 for text_file in map(lambda text_filename: os.path.join(text_data_dir, text_filename),fnmatch.filter(os.listdir(text_data_dir), '*.txt')):49 json_data = {}50 with io.open(text_file, 'rt', newline='') as file_object:51 for line_count, line in enumerate(file_object, start=1):52 if line_count in [2, 3, 4]:53 #du vide54 pass55 elif line_count == 1:56 # <Instance name>57 json_data['instanceC_name'] = line.strip()58 elif line_count == 5:59 # Custom number = 0, depart60 # <Custom number>, <X coordinate>, <Y coordinate>,61 # ... <Demand>, <type vehicle>,62 values = line.strip().split()63 json_data['depart'] = {64 'coordinates': {65 'x': float(values[1]),66 'y': float(values[2]),67 },68 'demand': float(values[3]),69 'type vehicle': int(values[4]),70 #'ready_time': float(values[5]),71 #'due_time': float(values[6]),72 #'service_time': float(values[7]),73 }74 else:75 # <Custom number>, <X coordinate>, <Y coordinate>,76 # ... <Demand>, <Type vehicle>77 values = line.strip().split()78 json_data[f'customer_{values[0]}'] = {79 'coordinates': {80 'x': float(values[1]),81 'y': float(values[2]),82 },83 'demand': float(values[3]),84 'type_vehicle': int(values[4]),85 #'ready_time': float(values[5]),86 #'due_time': float(values[6]),87 #'service_time': float(values[7]),88 }89 customers = ['depart'] + [f'customer_{x}' for x in range(1, 101)]90 json_data['distance_matrix'] = [[calculate_distance(json_data[customer1],91 json_data[customer2]) for customer1 in customers] for customer2 in customers]92 json_file_name = f"{json_data['instanceC_name']}.json"93 json_file = os.path.join(json_data_dir, json_file_name)94 print(f'Write to file: {json_file}')95 make_dirs_for_file(path=json_file)96 with io.open(json_file, 'wt', newline='') as file_object:97 dump(json_data, file_object, sort_keys=True, indent=4, separators=(',', ': '))98def text2jsonVehi(customize=False):99 text_data_dir = os.path.join(BASE_DIR, 'dataV', 'text_customizeV' if customize else 'text')100 json_data_dir = os.path.join(BASE_DIR, 'dataV', 'json_customizeV' if customize else 'json')101 for text_file in map(lambda text_filename: os.path.join(text_data_dir, text_filename),fnmatch.filter(os.listdir(text_data_dir), '*.txt')):102 json_data = {}103 with io.open(text_file, 'rt', newline='') as file_object:104 for line_count, line in enumerate(file_object, start=1):105 if line_count in [2,3]:106 #du vide107 pass108 elif line_count == 1:109 # <Instance name>110 json_data['instanceV_name'] = line.strip()111 else:112 # <VEHICLE ID>, <VEHICLE NAME>, <VEHICLE CAPACITY>,113 # ... <ID TYPE VEHICLE>114 values = line.strip().split()115 json_data[f'vehicle_{values[0]}'] = {116 'vehicle_name':values[1],117 'registration':values[2],118 'capacity': float(values[3]),119 'type_vehicle': int(values[4]),120 }121 vehicles = [f'vehicle_{x}' for x in range(1, 101)]122 json_file_name = f"{json_data['instanceV_name']}.json"123 json_file = os.path.join(json_data_dir, json_file_name)124 print(f'Write to file: {json_file}')125 make_dirs_for_file(path=json_file)126 with io.open(json_file, 'wt', newline='') as file_object:...

Full Screen

Full Screen

utils.py

Source:utils.py Github

copy

Full Screen

2import os3import json4import pickle5import csv6def make_dirs_for_file(pathname):7 try:8 os.makedirs(os.path.split(pathname)[0])9 except:10 pass11def exist(pathname, overwrite=False, display_info=True):12 def __path_type(pathname):13 if os.path.isfile(pathname):14 return 'File'15 if os.path.isdir(pathname):16 return 'Directory'17 if os.path.islink(pathname):18 return 'Symbolic Link'19 if os.path.ismount(pathname):20 return 'Mount Point'21 return 'Path'22 if os.path.exists(pathname):23 if overwrite:24 if display_info:25 print u'%s: %s exists. Overwrite.' % (__path_type(pathname), pathname)26 os.remove(pathname)27 return False28 else:29 if display_info:30 print u'%s: %s exists.' % (__path_type(pathname), pathname)31 return True32 else:33 if display_info:34 print u'%s: %s does not exist.' % (__path_type(pathname), pathname)35 return False36def load_text(pathname, display_info=True):37 if exist(pathname=pathname, display_info=display_info):38 with open(pathname, 'r') as f:39 return [line.strip() for line in f.readlines()]40def load_json(pathname, display_info=True):41 if exist(pathname=pathname, display_info=display_info):42 with open(pathname, 'r') as f:43 return json.load(f)44def dump_json(data, pathname, overwrite=False, display_info=True):45 make_dirs_for_file(pathname)46 if not exist(pathname=pathname, overwrite=overwrite, display_info=display_info):47 if display_info:48 print 'Write to file: %s' % pathname49 with open(pathname, 'w') as f:50 json.dump(data, f)51def load_model(pathname, display_info=True):52 if exist(pathname=pathname, display_info=display_info):53 with open(pathname, 'r') as f:54 return pickle.load(f)55def dump_model(model, pathname, overwrite=False, display_info=True):56 make_dirs_for_file(pathname)57 if not exist(pathname=pathname, overwrite=overwrite, display_info=display_info):58 if display_info:59 print 'Write to file: %s' % pathname60 with open(pathname, 'w') as f:61 pickle.dump(model, f)62def export_csv(data, fieldnames, pathname, overwrite=False, display_info=True):63 make_dirs_for_file(pathname)64 if not exist(pathname=pathname, overwrite=overwrite, display_info=display_info):65 if display_info:66 print 'Write to file: %s' % pathname67 with open(pathname, 'w') as f:68 writer = csv.DictWriter(f, fieldnames=fieldnames, dialect='excel')69 writer.writeheader()70 for row in data:71 writer.writerow(row)72def set_matplotlib_backend(backend=None):73 import matplotlib74 if matplotlib.get_backend() == 'MacOSX':75 matplotlib.use('TkAgg')76 if backend:77 matplotlib.use(backend)...

Full Screen

Full Screen

t2j.py

Source:t2j.py Github

copy

Full Screen

...10 '''gavrptw.uitls.calculate_distance(customer1, customer2)'''11 # print(customer1, customer2)12 return ((customer1['x'] - customer2['x'])**2 + \13 (customer1['y'] - customer2['y'])**2)**0.514def make_dirs_for_file(path):15 '''gavrptw.uitls.make_dirs_for_file(path)'''16 try:17 os.makedirs(os.path.dirname(path))18 except OSError:19 pass20def text2json(fn="", customize=False):21 22 text_data_dir = os.path.join(BASE_DIR, 'text_customize' if customize else 'text')23 json_data_dir = os.path.join(BASE_DIR, 'json_customize' if customize else 'json')24 25 if fn!="":26 print(f"fn={fn}")27 fn = os.path.join(text_data_dir, fn)28 print(f"fn = {fn}")29 for text_file in map(lambda text_filename: os.path.join(text_data_dir, text_filename), \30 fnmatch.filter(os.listdir(text_data_dir), '*.txt')):31 if fn != "" and text_file != f"{fn}.txt":32 continue33 json_data = {}34 with io.open(text_file, 'rt', newline='') as file_object:35 locations = []36 for line_count, line in enumerate(file_object, start=1):37 if line_count in [2, 3, 4, 6, 7, 8, 9]:38 pass39 elif line_count == 1:40 # <Instance name>41 json_data['name'] = line.strip()42 elif line_count == 5:43 # <Maximum vehicle number>, <Vehicle capacity>44 values = line.strip().split()45 json_data['number'] = int(values[0])46 json_data['capacity'] = int(values[1]) 47 else:48 # <Custom number>, <X coordinate>, <Y coordinate>,49 # ... <Demand>, <Ready time>, <Due date>, <Service time>50 values = line.strip().split()51 locations.append({ 52 'x': int(values[1]),53 'y': int(values[2]),54 'demand': int(values[3]),55 'start': int(values[4]),56 'end': int(values[5]),57 'service': int(values[6]),58 })59 # print(json_data)60 json_data['locs'] = locations61 json_data['dist'] = [[calculate_distance(a, b) for a in locations] for b in locations]62 json_file_name = f"{json_data['name']}.json"63 json_file = os.path.join(json_data_dir, json_file_name)64 print(f'Write to file: {json_file}')65 make_dirs_for_file(path=json_file)66 with io.open(json_file, 'wt', newline='') as file_object:67 dump(json_data, file_object, sort_keys=False, indent=4, separators=(',', ': '))68if __name__ == "__main__":69 # text2json()70 # Print total number of arguments71 print ('Total number of arguments:', format(len(sys.argv)))72 # Print all arguments73 print ('Argument List:', str(sys.argv))74 fn = ""75 if len(sys.argv) > 1:76 fn = sys.argv[1]77 ...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful