"Explicit is better than implicit."
super(FilterSortingInProfileForm, self).__init__(self, *args, **kwargs)
super(FilterSortingInProfileForm, self).__init__(*args, **kwargs)
# вариант 1
ws2.write(2, datr2.isoformat(), style1)
# вариант 2 - https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
ws2.write(2, datr2.strftime('%d-%m-%Y'), style1)
import re
import json
from ast import literal_eval
pattern = re.compile(r'data[= ]+(?P<dict>.*);')
raw = pattern.search(s).groupdict()
# if валидый JSON
j = json.loads(raw['dict'])
print(j['id'], j['url'])
# запасной вариант
# elif похоже на валидный python-dict
d = literal_eval(raw['dict'])
print(d['id'], d['url'])
import json
def model_by_plate(js, plate):
for car in json.loads(js)['cars']:
if car['plate'] == plate:
return car['model']
print(model_by_plate(data, 'E222EE177'))
for place in root.findall('Place'):
row = {}
for identity in place.findall('Identity'):
for placeid in identity.findall('PlaceId'):
header.add(placeid.tag)
row[placeid.tag] = placeid.text
for locationlist in place.findall('LocationList'):
for location in locationlist.findall('Location'):
for address in location.findall('Address'):
for parsed in address.findall('Parsed'):
for countrycode in parsed.findall('CountryCode'):
header.add(countrycode.tag)
row[countrycode.tag] = countrycode.text
places_data.append(row)
import csv
import xml.etree.ElementTree as ET
xml_data = """<?xml version="1.0"?>
<Root>
...
</Root>"""
root = ET.fromstring(xml_data)
header = set()
rows = []
for subroot in root:
row = {}
for level in subroot:
header.add(level.tag)
row[level.tag] = level.text
rows.append(row)
with open('out.csv', 'w') as file:
writer = csv.DictWriter(file, fieldnames=sorted(header))
writer.writeheader()
writer.writerows(rows)
for iitems in items:
for line in iitems.value.splitlines():
print(line)
from collections import defaultdict
def_dic = defaultdict(int)
for c in text:
def_dic[c] += 1
Есть ли метод, который поможет узнать расширение файла?
import os
destination = open('C:\\photo\\' + new_name, 'wb+')
# не делайте так...
# k = str(destination)
# file_path = k[26:-2]
filename = destination.name # имя файла
filepath = os.path.abspath(filename) # полный путь к файлу
file_extension = os.path.splitext(filename)[1] # вернется кортеж: [0] - имя файла, [1] - расширение
Данный метод не хочет сохранять файлы расширений zip,py и т.д. С чем это связано?
for chunk in file.chunks():
destination.write(chunk)
destination.close()
with open('C:\\photo\\' + new_name, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
ngrok http 80 # Для Nginx
ngrok http 8000 # Для Django dev-сервера
import requests
from bs4 import BeautifulSoup
LOGIN = ''
PASSWORD = ''
login_page = 'https://github.com/login'
auth_page = 'https://github.com/session'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:48.0) Gecko/20100101 Firefox/48.0'}
payload = {'login': LOGIN,
'password': PASSWORD,
'authenticity_token': '',
'commit': 'Sign in',
'utf8': '✓'}
with requests.Session() as session:
s = session.get(login_page, headers=headers)
soup = BeautifulSoup(s.text, 'html.parser')
auth_token = soup.find('input', attrs={'name': 'authenticity_token'})
payload['authenticity_token'] = auth_token['value']
s = session.post(auth_page, data=payload, headers=headers)
print(s.text)