我正在尝试逐行读取文本文件,然后逐行将其打印到excel工作表中
这是我迄今为止拥有的
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"
它将文本文件打印到excel表中,但所有内容都像这样放在一行中1
但我希望我的文本文件像这样打印出来2
如果你想知道我为什么使用[cellLocLastRow('A')]
,我会使用它而不是[A17]
,因为我将未知长度的文档打印到excel表中,因此它会计算行数。
def cellLocLastRow(colChar):
global lastRow
curRow = lastRow
lastRow += 1
return cellLoc(colChar, curRow)
文本文件格式如下:
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: #
您尝试过f.readlines()
方法吗?
with open(text, 'r') as f:
content1 = f.readlines()
这个脚本将返回一个包含所有文件行的列表,然后您可以轻松地执行任何您想要的操作。
使用pylightxl 这很容易
pip安装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”)