![](/img/trans.png)
[英]Python - Using csv and xlrd module to write multi-row excel file to one row csv file
[英]Transform multi-row string to csv in Python
獲取此字符串的最佳方法是什么:
1
2
3
4
a
b
c
d
1
2
3
4
a
b
c
d
1
2
3
4
a
b
c
d
並轉換為包含 6 列的 CSV?
期望輸出
是將導入 Pandas 的 CSV:
1,a,1,a,1,a
2,b,2,b,2,b
等等..
根據評論將所需的輸出更新為 6 行。
更新。 如果我將字符串分配給l
變量,我可以獲得這樣的第一行:
l.split()[0::4]
['1', 'a', '1', 'a', '1', 'a']
with open('data.txt', 'r') as f:
data = f.read().split("\n")
for i in range(4):
d = list()
for j in range(i, len(data), 4):
d.append(data[j])
with open('data.csv', 'a') as csv:
csv.write(','.join(d)+"\n")
盡管接受了 Art 的答案,但這是使用 Pandas 的另一種方式。 如果你使用這樣的東西,你就不需要在用 Pandas 導入之前導出數據。
import pandas as pd
myFile="lines_to_read2.txt"
myData = pd.DataFrame (columns=['col1', 'col2', 'col3','col4'])
mycolumns = 4
thisItem = list()
with open(myFile, 'r') as linesToRead:
for thisLine in linesToRead:
thisItem.append(thisLine.strip('\n, " "'))
if len(thisItem) == mycolumns:
myData = myData.append({'col1':thisItem[0],'col2':thisItem[1],'col3':thisItem[2],'col4':thisItem[3]}, ignore_index=True)
thisItem = list()
myData.to_csv('lines_as_csv_file.csv', index=False)
print(myData) # Full Table
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.