I wrote a code that passed information from a text file to excel.I sorted according to specific parameters I want to take from the file ("X,Y,O,P,E"). I neet to pass this information to sheet number 2. How can i do that ?
import xlsxwriter
def readFile(_path):
f = open(_path, "r")
return f.readlines()
def test():
file = open("Test.txt", 'r')
data = []
line_data = ""
for line in file:
if "_____ X" in line:
line_data = line[24:].replace("\t", "").replace("\n", "").split(":")[0]
elif "Y:" in line:
line_data = line.replace("\t", "").replace("\n", "").split(" ")[1]
elif "O:" in line:
line_data = line.replace("\t", "").replace("\n", "").split(" ")[1]
elif "P:" in line:
line_data = line.replace("\t", "").replace("\n", "").split(" ")[1]
elif "E=" in line:
line_data = line[21:].replace("\t", "").replace("\n", "").split[0]
if len(line_data) > 0:
data.append(line_data)
line_data = ""
writeToxlsx(data)
def writeToxlsx(data):
_output_path = "Book1.xlsx"
workbook = xlsxwriter.Workbook(_output_path)
worksheet = workbook.add_worksheet()
row = 0
for item in data:
worksheet.write(row, 1, item)
row += 1
workbook.close()
test()
Are you trying to write to an existing sheet? If so, you need to use openpyxl, not xlsxwriter. How to write/update data into cells of existing XLSX workbook using xlsxwriter in python
If you are writing to a new sheet, then where you have the line:
worksheet = workbook.add_worksheet()
instead write:
worksheet = workbook.add_worksheet('The Sheetname You Want')
or if you really need it to be the second sheet, you will have to create a dummy sheet for the front page. You can use the example provided here: Python XlsxWriter - Write to many sheets
Related
I wanted my code to have a button that lets me select the file I wanted to use instead of manually typing the file name in the code. My file is the file1234 as you can see below from my code. I also wanted to use ipywidgets if possible.
from openpyxl import Workbook
wb = Workbook()
with open('file1234.txt', encoding='utf-8') as blah:
row = 1
column = 1
ws = wb.active
lines = [line for line in blah.readlines()
if 'entered the channel' not in line
and 'left the channel' not in line]
for line in lines:
if column == 1:
## split the line and rejoin
value = " ".join(line.strip().split(' ')[2:])
else:
value = line.strip()
ws.cell(row=row, column=column, value=value)
if (column := column + 1) > 3:
row += 1
column = 1
for column_cells in ws.columns:
length = max(len(str(cell.value)) for cell in column_cells)
ws.column_dimensions[column_cells[0].column_letter].width = length
wb.save('txt_toexl.xlsx')
I have a code that is working for me in a Cinema 4d project. It is able to read 4 different data points and kick out outputs to the main project. Currently it is reading all of the lines of the csv file and I would like to pick one line and pull the data from that line only.
import c4d
import csv
def main():
path = Spreadsheet #Spreadsheet is an input filename path
with open(path, 'rb') as csv_file:
readed = csv.DictReader(csv_file,delimiter=',')
for i, row in enumerate(readed):
try:
Xcord = float(row["hc_x"])
Ycord = float(row["hc_y"])
Langle = float(row["launch_angle"])
Lspeed = float(row["launch_speed"])
except:
print "Error while reading - {}".format(row)
continue
global Output1
global Output2
global Output3
global Output4
Output1 = Xcord
Output2 = Ycord
Output3 = Langle
Output4 = Lspeed
This is about the first thing I have tried to code. So thanks.
csv.DictReader requires that you open the file with newline="" in order for it to parse the file correctly.
with open(path, 'rb', newline="") as csv_file:
readed = csv.DictReader(csv_file,delimiter=',')
You also don't have any condition to stop reading the file.
row_to_stop = 5
for i, row in enumerate(readed):
if i == row_to_stop:
Xcord = float(row["hc_x"])
Ycord = float(row["hc_y"])
Langle = float(row["launch_angle"])
Lspeed = float(row["launch_speed"])
break
If you only care about one line, don't look up and type cast values until you reach the line you care about.
I would like to pick one line and pull the data from that line only
The code below will return specific line (by index). You will have to split it and grab the data.
def get_interesting_line(file_name: str, idx: int):
cnt = 0
with open(file_name) as f:
while cnt != idx:
f.readline()
cnt += 1
return f.readline().strip()
# usage example below
print(get_interesting_line('data.txt',7))
I am trying to read a text file line by line and then print it to an excel sheet line by line
Here is what I have so far
for x in ABC:
print(f"{x}:")
sheet1[cellLocLastRow('A')] = f"{x}:"
try:
with open(f"./{x}/Log.txt") as f:
textRead= (f.read())
print(textRead)
sheet1[cellLocLastRow('A')] = textRead
except FileNotFoundError:
print("File does not exist")
sheet1[cellLocLastRow('A')] = "File does not exist"
It prints it out the text file to the excel sheet but all in one row like this
1
But I would like my text file to be printed out like this
2
If you were wondering why I am using [cellLocLastRow('A')] , I am using that instead of a [A17] because I am printing out unknown lengths of documents into an excel sheet and so it counts the rows.
def cellLocLastRow(colChar):
global lastRow
curRow = lastRow
lastRow += 1
return cellLoc(colChar, curRow)
The text file format is as follows:
TestName: TestName
TestName: Info::Info::Info::Info::f###::##.#ns
Total Errors: #
TestName: Info::Info::Info::Info::f###::##.#ns
Total Errors: #
TestName: Info::Info::Info::Info::f###::##.#ns
Total Errors: #
Did you tried f.readlines() method?
with open(text, 'r') as f:
content1 = f.readlines()
This script will return a list with all file's lines, then you can do whatever you want comfortably.
this is pretty easy with pylightxl
pip install pylightxl
lines = []
with open(“textfile.txt”) as f:
line = f.readline()
if not line:
break
lines.append(line)
import pylightxl as xl
db = xl.Database()
db.add_ws("Sheet1", {})
for i, line in enumerate(lines, start=1):
db.ws("Sheet1").update_index(i, 1,line)
xl.writexl(db, “output.xlsx”)
I'm trying to convert text file to excel sheet in python. The txt file contains data in the below specified formart
Column names: reg no, zip code, loc id, emp id, lastname, first name. Each record has one or more error numbers. Each record have their column names listed above the values. I would like to create an excel sheet containing reg no, firstname, lastname and errors listed in separate rows for each record.
How can I put the records in excel sheet ? Should I be using regular expressions ? And how can I insert error numbers in different rows for that corresponding record?
Expected output:
Here is the link to the input file:
https://github.com/trEaSRE124/Text_Excel_python/blob/master/new.txt
Any code snippets or suggestions are kindly appreciated.
Here is a draft code. Let me know if any changes needed:
# import pandas as pd
from collections import OrderedDict
from datetime import date
import csv
with open('in.txt') as f:
with open('out.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
#Remove inital clutter
while("INPUT DATA" not in f.readline()):
continue
header = ["REG NO", "ZIP CODE", "LOC ID", "EMP ID", "LASTNAME", "FIRSTNAME", "ERROR"]; data = list(); errors = list()
spamwriter.writerow(header)
print header
while(True):
line = f.readline()
errors = list()
if("END" in line):
exit()
try:
int(line.split()[0])
data = line.strip().split()
f.readline() # get rid of \n
line = f.readline()
while("ERROR" in line):
errors.append(line.strip())
line = f.readline()
spamwriter.writerow(data + errors)
spamwriter.flush()
except:
continue
# while(True):
# line = f.readline()
Use python-2 to run. The errors are appended as subsequent columns. It's slightly complicated the way you want it. I can fix it if still needed
Output looks like:
You can do this using the openpyxl library which is capable of depositing items directly into a spreadsheet. This code shows how to do that for your particular situation.
NEW_PERSON, ERROR_LINE = 1,2
def Line_items():
with open('katherine.txt') as katherine:
for line in katherine:
line = line.strip()
if not line:
continue
items = line.split()
if items[0].isnumeric():
yield NEW_PERSON, items
elif items[:2] == ['ERROR', 'NUM']:
yield ERROR_LINE, line
else:
continue
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws['A2'] = 'REG NO'
ws['B2'] = 'LASTNAME'
ws['C2'] = 'FIRSTNAME'
ws['D2'] = 'ERROR'
row = 2
for kind, data in Line_items():
if kind == NEW_PERSON:
row += 2
ws['A{:d}'.format(row)] = int(data[0])
ws['B{:d}'.format(row)] = data[-2]
ws['C{:d}'.format(row)] = data[-1]
first = True
else:
if first:
first = False
else:
row += 1
ws['D{:d}'.format(row)] = data
wb.save(filename='katherine.xlsx')
This is a screen snapshot of the result.
I want to compare the string in text file with the first colum in excel sheet
if the string in the file match any value in the first column I want to replace this string with the value in second column and save the changes to the text file
import numpy as np
wb = openpyxl.load_workbook('D:\\example.xlsx')
ws = wb.active
v = "D:\\A2.txt"
v = open(v).read()
row = 1
cell_addr = "A" + str(row)
next_cell = "B" + str(row)
while ws[cell_addr].value is not None:
# print(cell_addr, ws[cell_addr].value, type(ws[cell_addr].value))
j=1
for i in v:
if i == ws[cell_addr].value:
v.replace(i, ws[next_cell].value)
else:
print (i)
with open('D:\\A2.txt', 'w') as f:
f.write(i)
row += 1
cell_addr = "A" + str(row)
next_cell = "B" + str(row)
Something like this?
import openpyxl
xlsfile = 'example.xlsx'
txtfile = 'A2.txt'
with open(txtfile, 'r') as f:
v = f.read().split('\n')
new_v = list(v)
wb = openpyxl.load_workbook(xlsfile)
ws = wb.active
for cells in ws.rows:
val = cells[0].value
if val in v:
index = v.index(val)
new_v[index] = cells[1].value
with open(txtfile, 'w') as f:
f.write('\n'.join(new_v))