file = open("teszt.txt", "r") #opening the file
number_of_lines = 0
for line in file: #counts the lines that start with 2021/
line = line.strip("\n")
words = line.split()
if line[:5] == "2021/":
number_of_lines += 1
for x in file:
x = file.split()
print(x)
#print("Number of lines, start with 2021: ", number_of_lines)
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
text = "2021/03/01 08:28:22"
date = 1
while date <= number_of_lines: #writes the texts into cells
ws[f'A{date}'] = f'{text}'
date += 1
file.close()
wb.save("teszt.xlsx")
When I am trying to debug it just gives me this error:
Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'teszt.txt'
but when I am running the code nothing goes wrong.
The other thing is when I am trying to use split() it just doesn't work.
Related
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
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 have a bunch of xlsx files, named from 1 to 169 like '1.xlsx', '2.xlsx' and so on... But while going through for loop, that read that files, the code does not see any rows in the 11th file (nrows in 11th file always is 0, while it is not if you open it manually) and gives me the IndexError (while these files are not empty).
I have no idea of what is going on with that code.
import os, xlwt, xlrd
file_dir = 'docs/'
files = os.listdir(file_dir)
#Open file and, read neaded variables and write them
def r_file(path, file):
workbook = xlrd.open_workbook(path+file)
info_sheet = workbook.sheet_by_index(0)
data_sheet = workbook.sheet_by_index(1)
#cells with company info
print info_sheet.nrows
company_name = info_sheet.cell(3,3).value
company_leg_adress = info_sheet.cell(4,3).value
company_fact_adress = info_sheet.cell(5,3).value
#cells with answers
question_1 = data_sheet.cell(3,10).value
question_1_1 = data_sheet.cell(8,2).value
question_1_2 = data_sheet.cell(13,2).value
question_2 = data_sheet.cell(18,10).value
question_3 = data_sheet.cell(25,10).value
question_3_additional = [data_sheet.cell(nrow,10).value for nrow in range(30,48)]
question_4 = data_sheet.cell(51,2).value
question_5 = data_sheet.cell(56,2).value
#get full row in list
row_as_list = [company_name,company_leg_adress,company_fact_adress, question_1, question_1_1, question_1_2, question_2, question_3, question_4]+question_3_additional
return row_as_list
#write companies in file
def w_file(companies):
wb = xlwt.Workbook()
ws = wb.add_sheet('aggr', cell_overwrite_ok=True)
for company in companies:
row_as_list = r_file(file_dir,str(company)+'.xlsx')
for each_index in row_as_list:
ws.write(company, row_as_list.index(each_index) , each_index)
wb.save('aggregation.xls')
companies_amount = [x for x in range(1,170)]
w_file(companies_amount)
after running it, it returns:
Traceback (most recent call last):
File "/home/ubuntu/workspace/ex50/bin/writing.py", line 44, in <module>
w_file(companies_amount)
File "/home/ubuntu/workspace/ex50/bin/writing.py", line 36, in w_file
row_as_list = r_file(file_dir,str(company)+'.xlsx')
File "/home/ubuntu/workspace/ex50/bin/writing.py", line 13, in r_file
company_name = info_sheet.cell(3,3).value
File "/usr/local/lib/python2.7/dist-packages/xlrd-1.0.0-py2.7.egg/xlrd/sheet.py", line 401, in cell
self._cell_types[rowx][colx],
IndexError: list index out of range
and it makes it only on the 11th file (no matter wich file will be the 11th).
Can you tell me what is going on with that thing?
I have two files in a directory. One is a .CSV file and other is a Python script. Python code looks like this:
from pyx import *
import csv
import re
import sys
def write():
name = raw_input('Enter the name of .dat file: ') + '.dat'
file = open(name, "w")
for i in range(0, len(x_lista)-1):
file.write(x_lista[i])
file.write(" ")
file.write(y_lista[i])
file.write("\n")
file.close()
def read_CSV(x_lista, y_lista):
currency = raw_input('Enter the name of input .CSV file: ') + '.CSV'
#print currency
with open(currency, 'rb') as f:
reader = CSV.reader(f)
lista = list(reader)
print lista
if(currency == 'Frank' or 'USD'):
factor = 4
else:
factor = 3
for i in range (3, len(lista)-factor):
temp = (re.split(r'[";"]', (';'.join(lista[i]))))
temp1 = temp[0]
x_lista.append(temp1)
temp1 = temp[1]
y_lista.append(temp1)
print x_lista, y_lista
x_lista = []
y_lista = []
read_CSV(x_lista, y_lista)
write()
It takes what's in .CSV and by splitting/joining lists it produces a .DAT file consisting of two columns of data. Well... it does on Windows. However, when I try to compile it on Ubuntu I get this:
Enter the name of input .CSV file: Euro
Traceback (most recent call last):
File "nwb.py", line 46, in <module>
read_CSV(x_lista, y_lista)
File "nwb.py", line 22, in read_CSV
with open(currency, 'rb') as f:
IOError: [Errno 2] No such file or directory: 'Euro.CSV'
What would be the solution?
In Unix system file names are case sensitive.
For example: Euro.CSV and Euro.csv are different file names. Maybe the error is shown because of that
I have to create a function that reads a random line from a text file in python.
I have the following code but am not able to get it to work
import random
def randomLine(filename):
#Retrieve a random line from a file, reading through the file irrespective of the length
fh = open(filename.txt, "r")
lineNum = 0
it = ''
while 1:
aLine = fh.readline()
lineNum = lineNum + 1
if aLine != "":
# How likely is it that this is the last line of the file ?
if random.uniform(0,lineNum)<1:
it = aLine
else:
break
fh.close()
return it
print(randomLine(testfile.txt))
I got so far but,need help to go further, Please help
once the program is running i'm getting an error saying
print(randomLine(testfile.txt))
NameError: name 'testfile' is not defined
Here's a version that's been tested to work, and avoids empty lines.
Variable names are verbose for clarity.
import random
import sys
def random_line(file_handle):
lines = file_handle.readlines()
num_lines = len(lines)
random_line = None
while not random_line:
random_line_num = random.randint(0, num_lines - 1)
random_line = lines[random_line_num]
random_line = random_line.strip()
return random_line
file_handle = None
if len(sys.argv) < 2:
sys.stderr.write("Reading stdin\n")
file_handle = sys.stdin
else:
file_handle = open(sys.argv[1])
print(random_line(file_handle))
file_handle.close()