在我的文本文件顶部创建的空行 python
empty line created at the top of my text file python
myfile = open('curr_data.txt', 'w')
for row in stat_table.find_all('tr'):
for cell in row.find_all('td'):
myfile.write(cell.text + ',')
myfile.write("\n")
当它写入文本文件时,它会在文本文件的顶部添加一个空行。这是由于某种原因由“\n”引起的,因为当我删除它时就没有空行了。
就好像myfile.write("\n")
先于myfile.write(cell.text + ',')
被执行
我的输出看起来像
BLANK LINE HERE
1#BitcoinBTC#ZAR108,103.18#+0.16%#ZAR2.0T#Trade#
2#EthereumETH#ZAR2,148.71#+0.03%#ZAR233.8B#Trade#
3#XRPXRP#ZAR3.25#+2.40%#ZAR140.6B#Trade#
4#Bitcoin CashBCH#ZAR3,093.58#-0.92%#ZAR56.2B#Trade#
5#LitecoinLTC#ZAR652.31#-1.14%#ZAR41.6B#Trade#
我想要的样子
1#BitcoinBTC#ZAR108,103.18#+0.16%#ZAR2.0T#Trade#
2#EthereumETH#ZAR2,148.71#+0.03%#ZAR233.8B#Trade#
3#XRPXRP#ZAR3.25#+2.40%#ZAR140.6B#Trade#
4#Bitcoin CashBCH#ZAR3,093.58#-0.92%#ZAR56.2B#Trade#
5#LitecoinLTC#ZAR652.31#-1.14%#ZAR41.6B#Trade#
只检查是否有任何 row.find_all('td')
返回空列表(即 tr
没有 td
),如果空列表避免 myfile.write("\n")
myfile = open('curr_data.txt', 'w')
for row in stat_table.find_all('tr'):
data = row.find_all('td')
if data:
for cell in data:
myfile.write(cell.text + ',')
myfile.write("\n")
通常 html table 的开头行为 headers (th
).
如果你保证总是有一行 table header 那么你可以从第一个索引开始你的外循环切片。
for row in stat_table.find_all('tr')[1:]:
myfile = open('curr_data.txt', 'w')
for row in stat_table.find_all('tr'):
for cell in row.find_all('td'):
myfile.write(cell.text + ',')
myfile.write("\n")
当它写入文本文件时,它会在文本文件的顶部添加一个空行。这是由于某种原因由“\n”引起的,因为当我删除它时就没有空行了。
就好像myfile.write("\n")
先于myfile.write(cell.text + ',')
我的输出看起来像
BLANK LINE HERE
1#BitcoinBTC#ZAR108,103.18#+0.16%#ZAR2.0T#Trade#
2#EthereumETH#ZAR2,148.71#+0.03%#ZAR233.8B#Trade#
3#XRPXRP#ZAR3.25#+2.40%#ZAR140.6B#Trade#
4#Bitcoin CashBCH#ZAR3,093.58#-0.92%#ZAR56.2B#Trade#
5#LitecoinLTC#ZAR652.31#-1.14%#ZAR41.6B#Trade#
我想要的样子
1#BitcoinBTC#ZAR108,103.18#+0.16%#ZAR2.0T#Trade#
2#EthereumETH#ZAR2,148.71#+0.03%#ZAR233.8B#Trade#
3#XRPXRP#ZAR3.25#+2.40%#ZAR140.6B#Trade#
4#Bitcoin CashBCH#ZAR3,093.58#-0.92%#ZAR56.2B#Trade#
5#LitecoinLTC#ZAR652.31#-1.14%#ZAR41.6B#Trade#
只检查是否有任何 row.find_all('td')
返回空列表(即 tr
没有 td
),如果空列表避免 myfile.write("\n")
myfile = open('curr_data.txt', 'w')
for row in stat_table.find_all('tr'):
data = row.find_all('td')
if data:
for cell in data:
myfile.write(cell.text + ',')
myfile.write("\n")
通常 html table 的开头行为 headers (th
).
如果你保证总是有一行 table header 那么你可以从第一个索引开始你的外循环切片。
for row in stat_table.find_all('tr')[1:]: