def __init__(self, f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds): self.fieldnames = fieldnames self.restval = restval if extrasaction.lower() not in ('raise', 'ignore'): raise ValueError("extrasaction (%s) must be 'raise' or 'ignore'" % extrasaction) self.extrasaction = extrasaction self.writer = writer(f, dialect, *args, **kwds)
def search(): # Determine the location to be searched #city = input("Your Town/City: ") Put this in later to replace "town" variable town = "greenville" craigslist = 'http://' + town + ".craigslist.org/search/zip" print(craigslist) r = requests.get(craigslist).text # Scraping the site first_file = "C:\\Users\\Sam\\Documents\\first.csv" for pg in craigslist: soup = BeautifulSoup(r, 'html.parser') name_box = soup.find_next( "p") # need to find a way to get iterate thru name = name_box.text data = [] data.append(name) not_dup = [] if name != not_dup: not_dup.append(name) with open(first_file, 'a') as csv_file: writer = csv.writer(csv_file) for name in data: writer.writerow(name) print(name) else: continue print("done")
def __init__(self, f, fieldnames, restval = '', extrasaction = 'raise', dialect = 'excel', *args, **kwds): self.fieldnames = fieldnames self.restval = restval if extrasaction.lower() not in ('raise', 'ignore'): raise ValueError, "extrasaction (%s) must be 'raise' or 'ignore'" % extrasaction self.extrasaction = extrasaction self.writer = writer(f, dialect, *args, **kwds)
def append_list_as_row(file_name, list_of_elem): # Open file in append mode with open(file_name, 'a+', newline='') as write_obj: # Create a writer object from csv module csv_writer = writer(write_obj) # Add contents of list as last row in the csv file csv_writer.writerow(list_of_elem)
def main(): re2 = '(P2)|(P3)' rg2 = re.compile(re2, re.DOTALL) ext = [".log", ".log.0",".log.1",".log.2",".log.3",".log.4",".log.5",".log.6",".log.7",".log.8"] filelist = os.listdir('.') for files in filelist: if files.endswith(tuple(ext)): with open('test.csv','a') as out_file, open(files,'r') as in_file: writer = _csv.writer(out_file) writer.writerow(['time','LSPName','LSPID_TUNNELID','packets','TotalMbits','PPS','Ratebps','UTIL%','RESVBW_mbps']) for line in in_file: coulmns = line[:-1].split(' ') coulmns = list(filter(None, coulmns)) coulmns[0] = ' '.join(coulmns[:3]) del coulmns[1:3] if rg2.match(coulmns[1]): coulmns = list(filter(filtering,coulmns)) coulmns[2] = ' '.join(coulmns[2:8]) del coulmns[3:8] #if not(float(coulmns[7].strip("%")) == 0.00): # Converting BytePerSecond to Bits Per Second coulmns[4] = 8 * int(coulmns[4]) coulmns[6] = 8 * int(coulmns[6]) coulmns[8] = 8 * int(coulmns[8]) # Converting bps to Mbps coulmns[4] = coulmns[4]/(1000000) coulmns[6] = coulmns[6]/(1000000) coulmns[8] = coulmns[8]/(1000000) writer.writerow(coulmns)
def __init__(self, f, fieldnames, restval="", extrasaction="raise", dialect="excel", *args, **kwds): self.fieldnames = fieldnames self.restval = restval if extrasaction.lower() not in ("raise", "ignore"): raise ValueError, "extrasaction (%s) must be 'raise' or 'ignore'" % extrasaction self.extrasaction = extrasaction self.writer = writer(f, dialect, *args, **kwds)
def Crawl(): url = 'https://www.spiegel.de/international/' urlcrawled = 'https://www.spiegel.de' page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') weblinks = soup.find_all('a', {'href': True}) # retrieve news linke from main page of site with open('news.csv', 'w') as csv_file: csv_writer = writer(csv_file) # creating headers in the csv file headers = ['Title', 'SubTitle', 'Abstract', 'InsertedDate'] # writing a row of headers in the csv csv_writer.writerow(headers) urls = re.findall( '/international+[/a-z/]+(?:[-\w.]|(?:%[\da-fA-F]{2}))+.html', str(weblinks)) for u in urls: strurl = "{0}{1}".format(urlcrawled, u) # """Scrapes information from pages into items""" pagez = requests.get(strurl) soupz = BeautifulSoup(pagez.content, 'html.parser') # now lets loop through posts for tag in soupz.find_all("meta"): if tag.get("property", None) == "og:title": title = tag.get("content", None) elif tag.get("property", None) == "og:description": description = tag.get("content", None) elif tag.get("name", None) == "news_keywords": subtitle = tag.get("content", None) csv_writer.writerow( [title, subtitle, description, datetime.datetime.utcnow()]) csv_file.close()
def csv_writer(self, data, filename): if not os.path.isfile(filename) or os.stat(filename).st_size == 0: self.csv_new(filename) with open(filename, "a") as csv_file: writer = csv.writer(csv_file, delimiter=',') for line in data: writer.writerow(line)
def CSV_W(name, SN): with open( "F:\Python\Django_lamps_Json_login_telebot_002\Lamp_API_Login_Telebot\login/test_csv.csv", mode="a", encoding='utf-8') as w_file: file_writer = _csv.writer(w_file, delimiter=",", lineterminator="\r") file_writer.writerow([name, SN]) w_file.close()
def __init__(self, f, fieldnames, restval="", extrasaction="raise", dialect="excel", *args, **kwds): self.fieldnames = fieldnames # list of keys for the dict self.restval = restval # for writing short dicts if extrasaction.lower() not in ("raise", "ignore"): raise ValueError("extrasaction (%s) must be 'raise' or 'ignore'" % extrasaction) self.extrasaction = extrasaction self.writer = writer(f, dialect, *args, **kwds)
def serialize(cls, portfolio): output = StringIO() portfolio_writer = writer(output) portfolio_writer.writerow(['Symbol', 'Description', 'Country', 'Shares', 'Price', 'Currency', 'Total Value']) for h in portfolio.holdings.values(): portfolio_writer.writerow([h.symbol, h.description, h.country, "%.2f" % h.shares, cls._format(h.price), h.currency, cls._format(h.total_value())]) portfolio_writer.writerow(['CASH', 'Money Market Account', '-', '-', '-', portfolio.cash_currency, cls._format(portfolio.cash_value)]) portfolio_writer.writerow(['TOTAL', '-', '-', '-', '-', portfolio.cash_currency, cls._format(portfolio.value())]) return output
def csv_new(self, filename): DATA = [[ 'Type', 'URL', 'Listing Agent', 'Price', 'Address', 'Beds', 'Showers', 'Cars', 'Location Type', 'Size of the property', 'Description', 'Features' ]] with open(filename, 'w') as csv_file: writer = csv.writer(csv_file, delimiter=',') for line in DATA: writer.writerow(line)
def write(self, block, p_drive, file_name): if len(self.drivers) != len(block): raise Exception('Num blocks does not match num disks') f_name, ext = os.path.splitext(file_name) for i in range(len(block)): if i == p_drive: name = f_name + '_p.csv' with open(name, 'a', newline='') as csv: writer = _csv.writer(csv, delimiter=',') b = block[i] writer.writerow([b]) else: name = f_name + '_' + str(i) + '.csv' with open(name, 'a', newline='') as csv: writer = _csv.writer(csv, delimiter=',') b = block[i] writer.writerow([b])
def to_csv(self, filename=None): file = sys.stdout if filename is None else open(filename, "w") writer = _csv.writer(file) writer.writerow((self.__path + Histogram.__HEADER_BIN, self.__path + Histogram.__HEADER_COUNT)) for i in range(self.bin_count): writer.writerow((format(self.__bin(i), '.6f'), self.__counts[i])) if filename is not None: file.close()
def __init__(self, filename=None, cache=False, append=False): """ Constructor """ self.__filename = filename self.__cache = cache self.__has_header = False if self.__filename is None: self.__append = False self.__file = sys.stdout self.__writer = _csv.writer(self.__file) else: self.__append = append and os.path.exists(self.__filename) self.__file = open(self.__filename, "a" if self.__append else "w") self.__writer = CSVLogger(self.__file) if cache else _csv.writer( self.__file)
def export_results_clicked(self): file = QFileDialog.getSaveFileName(self, 'Save Keywords', '.', 'Excel (*.csv)')[0] if file: with open(file, 'wt', newline='') as file: w = writer(file) w.writerow(self.file_headers) for row in range(self.files.rowCount()): w.writerow([self.files.item(row, 0).text()] + [ self.files.item(row, i + 1).text() for i in range(self.keyword_list.count()) ])
def add_row_to_csv(csv_path, list_of_elements): """ This function takes as argument and then it adds rows to this csv file. :param csv_path: The path to csv. :param list_of_elements: The list you want to append. :return: Nothing """ with open(csv_path, 'a+', newline='') as write_obj: # Create a writer object from csv module csv_writer = writer(write_obj) # Add contents of list as last row in the csv file csv_writer.writerow(list_of_elements)
def readCSV(selfself): write_obj = open('data.csv', 'w+', newline='') csv_writer = writer(write_obj) for file in os.listdir("C:\\Users\\Alexandra\\Desktop\\CoronaNews"): if file.endswith(".CSV"): os.chdir(r'C:\Users\Alexandra\Desktop\CoronaNews') with open(file, 'r', encoding='utf8') as read_obj: csv_reader = reader(read_obj, delimiter='\t') line = next(csv_reader) if line is not None: for row in csv_reader: if row[37] != '' and row[45] != '' and row[37] != row[45] and "coronavirus" in row[60]: csv_writer.writerow([row[37], row[45], row[60]]) write_obj.close()
def exportCSV(): connection = mysql.connector.connect(host="34.82.241.205", user="******", password="******", database="FitnessTracker") curr = connection.cursor() with open('FitnessUsers.csv', 'w') as f: curr.execute( "SELECT FirstName, LastName, Description FROM Users Join Goals G on Users.GoalID = G.GoalID WHERE isDeleted = 0 ORDER BY UserID" ) rows = curr.fetchall() w = _csv.writer(f) for x in rows: w.writerow(rows)
def csvExport(in_list): with open('C://Users/Alec/Desktop/Video_Data_export.csv', 'ab') as vidprocess: global frame_number global frame_length process = csv.writer(vidprocess, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) write_list = [frame_number, frame_number * frame_length] for k in range(0, len(in_list)): write_list.append(in_list[k]) process.writerow(write_list) frame_number += 1 vidprocess.close()
def csvConvert(data): with open('C://Users/Alec/Desktop/Velocity_Data.csv', 'ab') as vidprocess: process = csv.writer(vidprocess, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) process.writerow(['Mission Start Time:', current_time]) process.writerow([ 'Car Number', 'Entry Time Offset', 'Entry X Position', 'Entry Y Position', 'Exit Time Offst', 'Exit X Position', 'Exit Y Position', 'Average Velocity' ]) for item in data: process.writerow(item) vidprocess.close()
def write(self, data, method='w'): """ Export data to CSV file. :param data: Either a list of tuples or a list of lists. :param method: File opening method. """ # Create list of lists from flat list data = data if isinstance(data[0], (list, set, tuple)) else [[d] for d in data] # Open file and write rows with open(self.file_path, method) as write: wr = csv_builtin.writer(write) wr.writerows(data) return self.file_path
def mapCountryCodesToNrAndEliminateDuplicates(self): lista = [] write_obj = open('final_result.csv', 'w+', newline='') csv_writer = writer(write_obj) with open('data.csv', 'r') as read_obj: csv_reader = reader(read_obj, delimiter=',') line = next(csv_reader) if line is not None: for row in csv_reader: if [row[0], row[1]] not in lista: lista.append([row[0], row[1]]) csv_writer.writerow([str(self.country_codes_dict[row[0]]), str(self.country_codes_dict[row[1]])]) if row[0] not in self.nodes: self.nodes.append(row[0]) if row[1] not in self.nodes: self.nodes.append(row[1]) print(len(self.nodes)) #cate noduri avem
def generate_face_data(): face_cascade = cv2.CascadeClassifier( 'data/haarcascade/haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('data/haarcascade/haarcascade_eye.xml') camera = cv2.VideoCapture(0) count = 0 while count <= TRAIN_IMAGES_COUNT: ret, frame = camera.read() frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(frame_gray, 1.3, 5) for face in faces: x, y, width, height = face cv2.rectangle(frame_gray, (x, y), (x + width, y + height), (255, 0, 0), 2) data_img = cv2.resize(frame_gray[y:y + height, x:x + width], (200, 200)) cv2.imwrite('data/face_data/' + str(count) + '.pgm', data_img) print("Image saved") count += 1 cv2.imshow("frame", frame) if cv2.waitKey(int(1000 / 12)) & 0xff == ord('q'): break csv_data = [] for root, dir, files in os.walk('data/face_data'): for file in files: if '.pgm' in file: csv_data.append([CSV_DATA_PATH + file, FACE_LABEL]) with open('data/face_data/facedata.csv', 'w') as file: writer = _csv.writer(file) writer.writerows(csv_data) camera.release() cv2.destroyAllWindows()
def toCsv(excel): import pyexcel import datetime from pyexcel._compact import OrderedDict book_dict = pyexcel.get_book_dict(file_name=excel) sheet1 = book_dict.get('Sheet1') zaglavlja = sheet1[0] lista = [] datumi = [] pozicija = 0 for z in zaglavlja: if ('iznos' in z.lower()): lista.append(pozicija) if 'datum' in z.lower(): datumi.append(pozicija) pozicija += 1 #print(lista) if (len(lista) > 0): for x in sheet1: for i in lista: x[i] = str(x[i]).replace(',', '.') if len(datumi) > 0: for x in sheet1: for i in datumi: if type(x[i]) == type(datetime.datetime.now()): x[i] = x[i].strftime('%d.%m.%Y') #x[i] = 'asasa' #x[i] = type(x[i]) #print(sheet1) import _csv as csv outfile = open( 'C:\\Users\\r103co62\\Desktop\\test\\Podaci za klijente 30.01.2019-21.02.2019.csv', 'w') writer = csv.writer(outfile, delimiter=';', lineterminator='\n', quotechar='"') writer.writerows(sheet1) outfile.close()
def main(): re2 = '(P2)|(P3)' rg2 = re.compile(re2, re.DOTALL) ext = [ ".log", ".log.0", ".log.1", ".log.2", ".log.3", ".log.4", ".log.5", ".log.6", ".log.7", ".log.8" ] filelist = os.listdir('.') for files in filelist: if files.endswith(tuple(ext)): with open('test.csv', 'a') as out_file, open(files, 'r') as in_file: writer = _csv.writer(out_file) writer.writerow([ 'time', 'LSPName', 'LSPID_TUNNELID', 'packets', 'TotalMbits', 'PPS', 'Ratebps', 'UTIL%', 'RESVBW_mbps' ]) for line in in_file: coulmns = line[:-1].split(' ') coulmns = list(filter(None, coulmns)) coulmns[0] = ' '.join(coulmns[:3]) del coulmns[1:3] if rg2.match(coulmns[1]): coulmns = list(filter(filtering, coulmns)) coulmns[2] = ' '.join(coulmns[2:8]) del coulmns[3:8] #if not(float(coulmns[7].strip("%")) == 0.00): # Converting BytePerSecond to Bits Per Second coulmns[4] = 8 * int(coulmns[4]) coulmns[6] = 8 * int(coulmns[6]) coulmns[8] = 8 * int(coulmns[8]) # Converting bps to Mbps coulmns[4] = coulmns[4] / (1000000) coulmns[6] = coulmns[6] / (1000000) coulmns[8] = coulmns[8] / (1000000) writer.writerow(coulmns)
def sample_page(request, model_title): res = "" for i in accounting.models.__dict__.keys(): if i.lower() == model_title: res = i break response = HttpResponse(content_type='text/csv') writer = csv.writer(response) if res == 'Поставщики': response[ 'Content-Disposition'] = 'attachment; filename="Providers.csv"' writer.writerow([ 'id поставщика', 'Тип организации', 'Телефон', 'Адрес', 'Другие контактные данные', 'Комментарий' ]) model = accounting.models.Поставщики for obj in model.objects.all().order_by('id_поставщика'): writer.writerow([ obj.id_поставщика, obj.id_типа_организации, obj.id_телефона, obj.id_адреса, obj.другие_контактные_данные, obj.комментарий ]) elif res == 'Адреса': response['Content-Disposition'] = 'attachment; filename="Address.csv"' writer.writerow( ['id адреса', 'Страна', 'Город', 'Улица', 'Дом', 'Квартира']) model = accounting.models.Адреса for obj in model.objects.all().order_by('id_адреса'): writer.writerow([ obj.id_адреса, obj.адрес.split(',')[0], obj.адрес.split(',')[1], obj.адрес.split(',')[2], obj.адрес.split(',')[3], obj.адрес.split(',')[4] if len(obj.адрес.split(',')) > 4 else "" ]) elif res == 'Должности': response[ 'Content-Disposition'] = 'attachment; filename="Positions.csv"' writer.writerow(['id должности', 'Название']) model = accounting.models.Должности for obj in model.objects.all().order_by('id_должности'): writer.writerow([obj.id_должности, obj.название]) elif res == 'ЕденицыИзмерения': response['Content-Disposition'] = 'attachment; filename="Units.csv"' writer.writerow( ['id единицы измерения', 'Название', 'Сокращенное название']) model = accounting.models.ЕденицыИзмерения for obj in model.objects.all().order_by('id_еденицы_измерения'): writer.writerow([ obj.id_еденицы_измерения, obj.название, obj.сокращенное_название ]) elif res == 'ЕденицыТехники': response[ 'Content-Disposition'] = 'attachment; filename="EngineeringUnits.csv"' writer.writerow( ['id единицы техники', 'Комплект', 'Названия единицы техники']) model = accounting.models.ЕденицыТехники for obj in model.objects.all().order_by('id_еденицы_техники'): writer.writerow([ obj.id_еденицы_техники, obj.id_комплекта, obj.id_названия_еденицы_техники ]) elif res == 'НазванияЕденицыТехники': response[ 'Content-Disposition'] = 'attachment; filename="TheNamesOfPiecesOfEquipment.csv"' writer.writerow(['id названия еденицы техники', 'Название']) model = accounting.models.НазванияЕденицыТехники for obj in model.objects.all().order_by('id_названия_еденицы_техники'): writer.writerow([obj.id_названия_еденицы_техники, obj.название]) elif res == 'Комнаты': response[ 'Content-Disposition'] = 'attachment; filename="Apartments.csv"' writer.writerow(['id комнаты', 'Номер комнаты']) model = accounting.models.Комнаты for obj in model.objects.all().order_by('id_комнаты'): writer.writerow([obj.id_комнаты, obj.номер_комнаты]) elif res == 'Комплекты': response['Content-Disposition'] = 'attachment; filename="Kits.csv"' writer.writerow( ['id комплекта', 'Рабочее место', 'Название комплекта']) model = accounting.models.Комплекты for obj in model.objects.all().order_by('id_комплекта'): writer.writerow([ obj.id_комплекта, obj.id_рабочего_места, obj.id_названия_комплекта ]) elif res == 'НазванияКомплекта': response[ 'Content-Disposition'] = 'attachment; filename="TitlesOfKit.csv"' writer.writerow(['id названия комплекта', 'Название']) model = accounting.models.НазванияКомплекта for obj in model.objects.all().order_by('id_названия_комплекта'): writer.writerow([obj.id_названия_комплекта, obj.название]) elif res == 'МоделиТехники': response[ 'Content-Disposition'] = 'attachment; filename="ModelsTechniques.csv"' writer.writerow( ['id модели техники', 'Название', 'Производитель', 'Типа техники']) model = accounting.models.МоделиТехники for obj in model.objects.all().order_by('id_модели_техники'): writer.writerow([ obj.id_модели_техники, obj.название, obj.id_производителя, obj.id_типа_техники ]) elif res == 'Накладные': response['Content-Disposition'] = 'attachment; filename="Overhead.csv"' writer.writerow( ['id накладной', 'Дата поставки', 'Поставщик', 'Номер накладной']) model = accounting.models.Накладные for obj in model.objects.all().order_by('id_накладной'): writer.writerow([ obj.id_накладной, obj.дата_поставки, obj.id_поставщика, obj.номер_накладной ]) elif res == 'ПППоНакладной': response[ 'Content-Disposition'] = 'attachment; filename="SoftwareInvoice.csv"' writer.writerow([ 'id пп по накладной', 'Накладная', 'Программный продукт', 'Цена за еденицу', 'Количество' ]) model = accounting.models.ПППоНакладной for obj in model.objects.all().order_by('id_пп_по_накладной'): writer.writerow([ obj.id_пп_по_накладной, obj.id_накладной, obj.id_пп, obj.цена_за_еденицу, obj.количество ]) elif res == 'ПрограммныеПродукты': response['Content-Disposition'] = 'attachment; filename="Software.csv"' writer.writerow([ 'id программного продукта', 'Название', 'Типа программного продукта' ]) model = accounting.models.ПрограммныеПродукты for obj in model.objects.all().order_by('id_пп'): writer.writerow([obj.id_пп, obj.название, obj.id_типа_пп]) elif res == 'Производители': response[ 'Content-Disposition'] = 'attachment; filename="Producers.csv"' writer.writerow(['id_производителя', 'Название']) model = accounting.models.Производители for obj in model.objects.all().order_by('id_производителя'): writer.writerow([obj.id_производителя, obj.название]) elif res == 'Рабочиеместа': response[ 'Content-Disposition'] = 'attachment; filename="Workplaces.csv"' writer.writerow( ['id рабочего места', 'Комната', 'Номер рабочего места']) model = accounting.models.Рабочиеместа for obj in model.objects.all().order_by('id_рабочего_места'): writer.writerow([ obj.id_рабочего_места, obj.id_комнаты, obj.номер_рабочего_места ]) elif res == 'Сотрудники': response['Content-Disposition'] = 'attachment; filename="Employee.csv"' writer.writerow([ 'id сотрудника', 'Фамилия', 'Имя', 'Отчество', 'Дата рождения', 'Должность', 'Рабочее место', 'Пол', 'Телефон', 'Адреса' ]) model = accounting.models.Сотрудники for obj in model.objects.all().order_by('id_сотрудника'): writer.writerow([ obj.id_сотрудника, obj.фамилия, obj.имя, obj.отчество, obj.дата_рождения, obj.id_должности, obj.id_рабочего_места, "мужской" if obj.пол == 'м' else "женский", obj.id_телефона, obj.id_адреса ]) elif res == 'Списания': response[ 'Content-Disposition'] = 'attachment; filename="Write-off.csv"' writer.writerow( ['id списания', 'Дата списания', 'Сотрудник', 'Заголовок']) model = accounting.models.Списания for obj in model.objects.all().order_by('id_списание'): writer.writerow( [obj.id_списание, obj.дата, obj.id_сотрудника, obj.заголовок]) elif res == 'СписаннаяТехника': response[ 'Content-Disposition'] = 'attachment; filename="DecommissionedEquipment.csv"' writer.writerow([ 'id списанной техники', 'Эземпляр техники', 'Списание', 'Причина' ]) model = accounting.models.СписаннаяТехника for obj in model.objects.all().order_by('id_списанной_техники'): writer.writerow([ obj.id_списанной_техники, obj.id_экземпляра_техники, obj.id_списания, obj.причина ]) elif res == 'Телефоны': response['Content-Disposition'] = 'attachment; filename="Phones.csv"' writer.writerow(['id телефона', 'Телефон']) model = accounting.models.Телефоны for obj in model.objects.all().order_by('id_телефона'): writer.writerow([obj.id_телефона, obj.телефон]) elif res == 'ТехникаПоНакладной': response[ 'Content-Disposition'] = 'attachment; filename="TechnicianSurface.csv"' writer.writerow([ 'id техники по накладной', 'Накладная', 'Модель техники', 'Количество', 'Цена за еденицу' ]) model = accounting.models.ТехникаПоНакладной for obj in model.objects.all().order_by('id_техники_по_накладной'): writer.writerow([ obj.id_техники_по_накладной, obj.id_накладной, obj.id_модели_техники, obj.количество, obj.цена_за_еденицу ]) elif res == 'ТипыОрганизаций': response[ 'Content-Disposition'] = 'attachment; filename="TypesOfOrganizations.csv"' writer.writerow(['id типа организации', 'Аббревиатура', 'Название']) model = accounting.models.ТипыОрганизаций for obj in model.objects.all().order_by('id_типа_организации'): writer.writerow( [obj.id_типа_организации, obj.аббревиатура, obj.название]) elif res == 'ТипыПП': response[ 'Content-Disposition'] = 'attachment; filename="TypesOfSoftware.csv"' writer.writerow(['id типа пп', 'Название']) model = accounting.models.ТипыПП for obj in model.objects.all().order_by('id_типа_пп'): writer.writerow([obj.id_типа_пп, obj.название]) elif res == 'ТипыТехники': response[ 'Content-Disposition'] = 'attachment; filename="TypesOfVehicles.csv"' writer.writerow(['id типа техники', 'Название']) model = accounting.models.ТипыТехники for obj in model.objects.all().order_by('id_типа_техники'): writer.writerow([obj.id_типа_техники, obj.название]) elif res == 'ТипыУлиц': response[ 'Content-Disposition'] = 'attachment; filename="TypesOfStreets.csv"' writer.writerow(['id типа улицы', 'Название', 'Сокращенное название']) model = accounting.models.ТипыУлиц for obj in model.objects.all().order_by('id_типа_улицы'): writer.writerow( [obj.id_типа_улицы, obj.название, obj.сокращенное_название]) elif res == 'УстановленныеПП': response[ 'Content-Disposition'] = 'attachment; filename="InstalledSoftware.csv"' writer.writerow([ 'id установленного пп', 'пп по накладной', 'Серийный_ключ', 'Экземпляр техники' ]) model = accounting.models.УстановленныеПП for obj in model.objects.all().order_by('id_установленногопп'): writer.writerow([ obj.id_установленногопп, obj.id_пп_по_накладной, obj.серийный_ключ, obj.id_экземпляра_техники ]) elif res == 'Характеристики': response[ 'Content-Disposition'] = 'attachment; filename="Characteristics.csv"' writer.writerow(['id характеристики', 'Название', 'Единица измерения']) model = accounting.models.Характеристики for obj in model.objects.all().order_by('id_характеристики'): writer.writerow([ obj.id_характеристики, obj.название, obj.id_еденицы_измерения ]) elif res == 'ХарактеристикиМодели': response[ 'Content-Disposition'] = 'attachment; filename="CharacteristicsOfModel.csv"' writer.writerow([ 'id характеристики модели', 'Характеристика', 'Модель техники', 'Значение' ]) model = accounting.models.ХарактеристикиМодели for obj in model.objects.all().order_by('id_характеристики_модели'): writer.writerow([ obj.id_характеристики_модели, obj.id_характеристики, obj.id_модели_техники, obj.значение ]) elif res == 'ЭкземплярыТехники': response[ 'Content-Disposition'] = 'attachment; filename="EquipmentItems.csv"' writer.writerow([ 'id экземпляра техники', 'Единица техники', 'Заводской код', 'Инвентарный номер', 'Техника по накладной', 'Дата гарантии', 'Списание' ]) model = accounting.models.ЭкземплярыТехники for obj in model.objects.all().order_by('id_экземпляра_техники'): writer.writerow([ obj.id_экземпляра_техники, obj.id_еденицы_техники, obj.заводской_код, obj.инвентарный_номер, obj.id_техники_по_накладной, obj.дата_гарантии, obj.id_списания ]) return response
distribution_y = norm(0, 70) distribution_z = norm(0, 0) elif option == 'flat_vertical': distribution_x = norm(0, 50) distribution_y = norm(0, 0) distribution_z = norm(0, 90) elif option == 'tube': distribution_x = norm(0, 50) distribution_y = distribution_x distribution_z = norm(0, 90) else: distribution_x = norm(0, 80) distribution_y = norm(0, 80) distribution_z = norm(0, 80) x = distribution_x.rvs(size=num_points) y = distribution_y.rvs(size=num_points) z = distribution_z.rvs(size=num_points) points = zip(x, y, z) return points if __name__ == '__main__': # main() cloud_points = generate_points(10000, 'random') with open('Lidar.csv', 'w', encoding='utf-8', newline='\n') as csv_file: csv_file_writer = writer(csv_file) for point in cloud_points: csv_file_writer.writerow(point) print(f'Done')
import _csv import _sqlite3 writer = _csv.writer(open("out.csv", 'w')) writer.writerow(['name', 'address', 'phone', 'etc']) writer.writerow(['bob', '2 main st', '703', 'yada']) writer.writerow(['mary', '3 main st', '704', 'yada'])
def CSV_W(): with open("test_csv.csv", mode="a", encoding='utf-8') as w_file: file_writer = _csv.writer(w_file, delimiter=",", lineterminator="\r") file_writer.writerow(["tert", "sn"]) w_file.close()
]) print(Name) print(Club) print(Nation) print(League) print(Skills) print(Weak_Foot) print(Intl_Rep) print(Foot) print(Height) print(Weight) print(Revision) print(Def_WR) print(Att_WR) print(Added_on) print(Origin) print(R_Face) print(B_Type) print(Age) with open('result1.csv', 'w', newline='') as file: writer = _csv.writer(file) headers = [ 'Num', 'Name', 'Club', 'Nation', 'League', 'Skills', 'Weak_Foot', 'Intl.Rep', 'Foot', 'Height', 'Weight', 'Revision', 'Def_WR', 'Att_WR', 'Added_on', 'Origin', 'R.Face', 'B.Type', 'Age' ] writer.writerow(headers) for data in datas: writer.writerow(data)
# and then write to different table specified by the user. # Arguments: # sys.argv[1] - project's base folder where the project files are located # sys.argv[2] - output folder of the project where the RunTimes.csv is located # sys.argv[3] - the list of jobs have been executed in the project # sys.argv[4] - user-defined output table name + .csv # sys.argv[5..] - Other arguments specified in the RVX file import sys import _csv import math ifile = open(sys.argv[2] + "RunTimes.csv", "rt") reader = _csv.reader(ifile) ofile = open(sys.argv[2] + sys.argv[4], "wb") writer = _csv.writer(ofile) rownum = 0 timelist = [] for row in reader: # Save header row. if rownum == 0: header = row[0:3] header.append("CpuTime") writer.writerow(header) else: time = [float(t) for t in row[5:]] seconds = time[0] * 3600 + time[1] * 60 + time[2] timelist.append(seconds) temprow = row[0:3] temprow.append(seconds)
def sample_page(request, model_title): res = "" for i in accounting.models.__dict__.keys(): if i.lower() == model_title: res = i break response = HttpResponse(content_type='text/csv') writer = csv.writer(response) if res == 'Поставщики': response['Content-Disposition'] = 'attachment; filename="Providers.csv"' writer.writerow(['id поставщика', 'Тип организации', 'Телефон', 'Адрес', 'Другие контактные данные', 'Комментарий']) model = accounting.models.Поставщики for obj in model.objects.all().order_by('id_поставщика'): writer.writerow([obj.id_поставщика, obj.id_типа_организации, obj.id_телефона, obj.id_адреса, obj.другие_контактные_данные, obj.комментарий]) elif res == 'Адреса': response['Content-Disposition'] = 'attachment; filename="Address.csv"' writer.writerow(['id адреса', 'Страна', 'Город', 'Улица', 'Дом', 'Квартира']) model = accounting.models.Адреса for obj in model.objects.all().order_by('id_адреса'): writer.writerow([obj.id_адреса, obj.адрес.split(',')[0], obj.адрес.split(',')[1], obj.адрес.split(',')[2], obj.адрес.split(',')[3], obj.адрес.split(',')[4] if len(obj.адрес.split(',')) > 4 else ""]) elif res == 'Должности': response['Content-Disposition'] = 'attachment; filename="Positions.csv"' writer.writerow(['id должности', 'Название']) model = accounting.models.Должности for obj in model.objects.all().order_by('id_должности'): writer.writerow([obj.id_должности, obj.название]) elif res == 'ЕденицыИзмерения': response['Content-Disposition'] = 'attachment; filename="Units.csv"' writer.writerow(['id единицы измерения', 'Название', 'Сокращенное название']) model = accounting.models.ЕденицыИзмерения for obj in model.objects.all().order_by('id_еденицы_измерения'): writer.writerow([obj.id_еденицы_измерения, obj.название, obj.сокращенное_название]) elif res == 'ЕденицыТехники': response['Content-Disposition'] = 'attachment; filename="EngineeringUnits.csv"' writer.writerow(['id единицы техники', 'Комплект', 'Названия единицы техники']) model = accounting.models.ЕденицыТехники for obj in model.objects.all().order_by('id_еденицы_техники'): writer.writerow([obj.id_еденицы_техники, obj.id_комплекта, obj.id_названия_еденицы_техники]) elif res == 'НазванияЕденицыТехники': response['Content-Disposition'] = 'attachment; filename="TheNamesOfPiecesOfEquipment.csv"' writer.writerow(['id названия еденицы техники', 'Название']) model = accounting.models.НазванияЕденицыТехники for obj in model.objects.all().order_by('id_названия_еденицы_техники'): writer.writerow([obj.id_названия_еденицы_техники, obj.название]) elif res == 'Комнаты': response['Content-Disposition'] = 'attachment; filename="Apartments.csv"' writer.writerow(['id комнаты', 'Номер комнаты']) model = accounting.models.Комнаты for obj in model.objects.all().order_by('id_комнаты'): writer.writerow([obj.id_комнаты, obj.номер_комнаты]) elif res == 'Комплекты': response['Content-Disposition'] = 'attachment; filename="Kits.csv"' writer.writerow(['id комплекта', 'Рабочее место', 'Название комплекта']) model = accounting.models.Комплекты for obj in model.objects.all().order_by('id_комплекта'): writer.writerow([obj.id_комплекта, obj.id_рабочего_места, obj.id_названия_комплекта]) elif res == 'НазванияКомплекта': response['Content-Disposition'] = 'attachment; filename="TitlesOfKit.csv"' writer.writerow(['id названия комплекта', 'Название']) model = accounting.models.НазванияКомплекта for obj in model.objects.all().order_by('id_названия_комплекта'): writer.writerow([obj.id_названия_комплекта, obj.название]) elif res == 'МоделиТехники': response['Content-Disposition'] = 'attachment; filename="ModelsTechniques.csv"' writer.writerow(['id модели техники', 'Название', 'Производитель', 'Типа техники']) model = accounting.models.МоделиТехники for obj in model.objects.all().order_by('id_модели_техники'): writer.writerow([obj.id_модели_техники, obj.название, obj.id_производителя, obj.id_типа_техники]) elif res == 'Накладные': response['Content-Disposition'] = 'attachment; filename="Overhead.csv"' writer.writerow(['id накладной', 'Дата поставки', 'Поставщик', 'Номер накладной']) model = accounting.models.Накладные for obj in model.objects.all().order_by('id_накладной'): writer.writerow([obj.id_накладной, obj.дата_поставки, obj.id_поставщика, obj.номер_накладной]) elif res == 'ПППоНакладной': response['Content-Disposition'] = 'attachment; filename="SoftwareInvoice.csv"' writer.writerow(['id пп по накладной', 'Накладная', 'Программный продукт', 'Цена за еденицу', 'Количество']) model = accounting.models.ПППоНакладной for obj in model.objects.all().order_by('id_пп_по_накладной'): writer.writerow([obj.id_пп_по_накладной, obj.id_накладной, obj.id_пп, obj.цена_за_еденицу, obj.количество]) elif res == 'ПрограммныеПродукты': response['Content-Disposition'] = 'attachment; filename="Software.csv"' writer.writerow(['id программного продукта', 'Название', 'Типа программного продукта']) model = accounting.models.ПрограммныеПродукты for obj in model.objects.all().order_by('id_пп'): writer.writerow([obj.id_пп, obj.название, obj.id_типа_пп]) elif res == 'Производители': response['Content-Disposition'] = 'attachment; filename="Producers.csv"' writer.writerow(['id_производителя', 'Название']) model = accounting.models.Производители for obj in model.objects.all().order_by('id_производителя'): writer.writerow([obj.id_производителя, obj.название]) elif res == 'Рабочиеместа': response['Content-Disposition'] = 'attachment; filename="Workplaces.csv"' writer.writerow(['id рабочего места', 'Комната', 'Номер рабочего места']) model = accounting.models.Рабочиеместа for obj in model.objects.all().order_by('id_рабочего_места'): writer.writerow([obj.id_рабочего_места, obj.id_комнаты, obj.номер_рабочего_места]) elif res == 'Сотрудники': response['Content-Disposition'] = 'attachment; filename="Employee.csv"' writer.writerow(['id сотрудника', 'Фамилия', 'Имя', 'Отчество', 'Дата рождения', 'Должность', 'Рабочее место', 'Пол', 'Телефон', 'Адреса']) model = accounting.models.Сотрудники for obj in model.objects.all().order_by('id_сотрудника'): writer.writerow([obj.id_сотрудника, obj.фамилия, obj.имя, obj.отчество, obj.дата_рождения, obj.id_должности, obj.id_рабочего_места, "мужской" if obj.пол == 'м' else "женский", obj.id_телефона, obj.id_адреса]) elif res == 'Списания': response['Content-Disposition'] = 'attachment; filename="Write-off.csv"' writer.writerow(['id списания', 'Дата списания', 'Сотрудник', 'Заголовок']) model = accounting.models.Списания for obj in model.objects.all().order_by('id_списание'): writer.writerow([obj.id_списание, obj.дата, obj.id_сотрудника, obj.заголовок]) elif res == 'СписаннаяТехника': response['Content-Disposition'] = 'attachment; filename="DecommissionedEquipment.csv"' writer.writerow(['id списанной техники', 'Эземпляр техники', 'Списание', 'Причина']) model = accounting.models.СписаннаяТехника for obj in model.objects.all().order_by('id_списанной_техники'): writer.writerow([obj.id_списанной_техники, obj.id_экземпляра_техники, obj.id_списания, obj.причина]) elif res == 'Телефоны': response['Content-Disposition'] = 'attachment; filename="Phones.csv"' writer.writerow(['id телефона', 'Телефон']) model = accounting.models.Телефоны for obj in model.objects.all().order_by('id_телефона'): writer.writerow([obj.id_телефона, obj.телефон]) elif res == 'ТехникаПоНакладной': response['Content-Disposition'] = 'attachment; filename="TechnicianSurface.csv"' writer.writerow(['id техники по накладной', 'Накладная', 'Модель техники', 'Количество', 'Цена за еденицу']) model = accounting.models.ТехникаПоНакладной for obj in model.objects.all().order_by('id_техники_по_накладной'): writer.writerow([obj.id_техники_по_накладной, obj.id_накладной, obj.id_модели_техники, obj.количество, obj.цена_за_еденицу]) elif res == 'ТипыОрганизаций': response['Content-Disposition'] = 'attachment; filename="TypesOfOrganizations.csv"' writer.writerow(['id типа организации', 'Аббревиатура', 'Название']) model = accounting.models.ТипыОрганизаций for obj in model.objects.all().order_by('id_типа_организации'): writer.writerow([obj.id_типа_организации, obj.аббревиатура, obj.название]) elif res == 'ТипыПП': response['Content-Disposition'] = 'attachment; filename="TypesOfSoftware.csv"' writer.writerow(['id типа пп', 'Название']) model = accounting.models.ТипыПП for obj in model.objects.all().order_by('id_типа_пп'): writer.writerow([obj.id_типа_пп, obj.название]) elif res == 'ТипыТехники': response['Content-Disposition'] = 'attachment; filename="TypesOfVehicles.csv"' writer.writerow(['id типа техники', 'Название']) model = accounting.models.ТипыТехники for obj in model.objects.all().order_by('id_типа_техники'): writer.writerow([obj.id_типа_техники, obj.название]) elif res == 'ТипыУлиц': response['Content-Disposition'] = 'attachment; filename="TypesOfStreets.csv"' writer.writerow(['id типа улицы', 'Название', 'Сокращенное название']) model = accounting.models.ТипыУлиц for obj in model.objects.all().order_by('id_типа_улицы'): writer.writerow([obj.id_типа_улицы, obj.название, obj.сокращенное_название]) elif res == 'УстановленныеПП': response['Content-Disposition'] = 'attachment; filename="InstalledSoftware.csv"' writer.writerow(['id установленного пп', 'пп по накладной', 'Серийный_ключ', 'Экземпляр техники']) model = accounting.models.УстановленныеПП for obj in model.objects.all().order_by('id_установленногопп'): writer.writerow([obj.id_установленногопп, obj.id_пп_по_накладной, obj.серийный_ключ, obj.id_экземпляра_техники]) elif res == 'Характеристики': response['Content-Disposition'] = 'attachment; filename="Characteristics.csv"' writer.writerow(['id характеристики', 'Название', 'Единица измерения']) model = accounting.models.Характеристики for obj in model.objects.all().order_by('id_характеристики'): writer.writerow([obj.id_характеристики, obj.название, obj.id_еденицы_измерения]) elif res == 'ХарактеристикиМодели': response['Content-Disposition'] = 'attachment; filename="CharacteristicsOfModel.csv"' writer.writerow(['id характеристики модели', 'Характеристика', 'Модель техники', 'Значение']) model = accounting.models.ХарактеристикиМодели for obj in model.objects.all().order_by('id_характеристики_модели'): writer.writerow([obj.id_характеристики_модели, obj.id_характеристики, obj.id_модели_техники, obj.значение]) elif res == 'ЭкземплярыТехники': response['Content-Disposition'] = 'attachment; filename="EquipmentItems.csv"' writer.writerow(['id экземпляра техники', 'Единица техники', 'Заводской код', 'Инвентарный номер', 'Техника по накладной', 'Дата гарантии', 'Списание']) model = accounting.models.ЭкземплярыТехники for obj in model.objects.all().order_by('id_экземпляра_техники'): writer.writerow([obj.id_экземпляра_техники, obj.id_еденицы_техники, obj.заводской_код, obj.инвентарный_номер, obj.id_техники_по_накладной, obj.дата_гарантии, obj.id_списания]) return response
from _csv import writer import sys sys.path.append("../") from hw3.solution import run with open("grid.csv", "w+") as f: csv_writer = writer(f) # write header csv_writer.writerow( ["n_epochs", "L", "C", "batch_size", "lr", "training_error"]) for L in [1e6]: for C in [1, 10, 100]: print(L, C) training_error = run( n_epochs=100, L=L, C=C, lr=1e-6, batch_size=2048, ) csv_writer.writerow([1, L, C, 2048, 1e-6, training_error])
while i < len(list_): str_ += str(list_[i]) str_ += " " i += 1 return str_ biggest_id = 0 freed_id = [] is_up_to_date = 1 try: file = open('database.csv', 'r+') except FileNotFoundError: file = open('database.csv', 'w+') writer = _csv.writer(file, delimiter=';') reader = _csv.reader(file, delimiter=';') id_to_person = {} last_name_to_id = {} first_name_to_id = {} patronymic_to_id = {} phone_number_to_id = {} date_of_birth_to_id = {} def print_line(): print("---------------------------------------------------------------------") def write_header():
from __future__ import absolute_import, unicode_literals import _csv import io reader = type(_csv.reader(io.StringIO(''))) writer = type(_csv.writer(io.StringIO()))
# *-coding:utf-8-*- import re import requests import importlib import sys importlib.reload(sys) import _csv with open('C:/Users/yinyy/Desktop/Second_type111.csv','w',newline='') as csvfile: writer =_csv.writer(csvfile) writer.writerow(["gender","type","PRESENCE OF RETINOPATHY","duration","hba1c%","systolic","1_year","5_year","10_year"]) url='http://retinarisk.com/calculator/bout_interactive.php' for PRESENCE in range(0,2): if PRESENCE==0: Static='Yes' #0 else: Static='No' #1 for gender in range(0,2): if gender==0: Static2='Male' #0 else: Static2='Female' #1 for hbac in range(0,13,2): for DURATION in range(0,40,4): for SYSTOLIC in range(60,180,6): header={ 'Accept':'*/*', 'Accept-Encoding':'gzip, deflate', 'Accept-Language':'zh-CN,zh;q=0.8', 'Connection':'keep-alive', 'Content-Length':'143',