簡體   English   中英

如何通過python(來自txt文件)將很長的行數據分成兩列

[英]how to split a very long row data into two column by python (from txt file)

我有一個txt文件,其中的datat行很長(例如,如下所示)

234.45  234.3455 667.4556 566.3311 332.333 564.322 554.2564 21.203 

我想用python讀取.txt文件,並想將數據分成兩列,如下所示:

234.45  234.3455
667.4556 566.3311
332.333 564.322
554.2564 21.203

我是python新手,不確定如何加載讀取的.txt文件並將數據拆分為列? 有人可以幫助我嗎? 謝謝你

假設您有一個名為“ sample.txt”的文件。 你可以做

f = open('sample.txt', 'r')

這將打開文件,現在可以讀取文件的內容,您可以使用方法readlines ,該方法將返回行或行的列表,無論您叫它們什么。 現在,每一行都是字符串,可以說此數據由空格分隔,您可以在線使用split方法生成列。

因此,您的代碼可能是這樣的

f = open('sample.txt', 'r')
lines = f.readlines()
for line in lines:
    columns = line.split(' ')
    print(columns)

希望能幫助到你!

打開文件

fp = open('concernedfile.txt', 'r')

讀取以字符串形式返回文件中的所有內容。

拆分將每個數字分成列表項。

http://www.tutorialspoint.com/python/string_split.htm上了解有關拆分的更多信息

before_split = fp.read()
data = before_split.split()

查找列表的長度並附加數據

x = len(data)
col1 = []
col2 = []
for i in range(0,x):
    if (i % 2 == 0):
        col1.append(data[i])
    else:
        col2.append(data[i])

Zip可以幫助您匯總數據結構

combinedcol = zip(col1, col2)

將列打印為元組。 您可以在此處輕松進行更改。

for i in combinedcol:
        print i

本質上,您遍歷每個項目,如果列表中該項目的索引是偶數,則將其添加到col1 ,否則將其添加到col2

這適用於以任意數量的空格分隔的項目

import re
with open("test.txt") as f:
    inputString = f.read()

#remove all extra spaces so all items separated by only one space
inputString = re.sub(r" +", " ", inputString)

itemsInString = inputString.split(" ")

col1 = []
col2 = []
for index, item in enumerate(itemsInString):
    if index % 2 == 0:
        col1.append(float(item))
    else:
        col2.append(float(item))

print(col1)
print(col2)

這為您提供以下內容:
col1 = [234.45, 667.4556, 332.333, 554.2564]
col2 = [234.3455, 566.3311, 564.322, 21.203]

將其寫回到文件中:

writeString = ""
for item in zip(col1, col2):
    writeString += str(item[0]) + " " + str(item[1]) + "\n"

with open("outfile.txt", "w") as f:
    f.write(writeString)


這是一種無需字符串連接即可寫入文件的更優化的方法,但不清楚

with open("outfile.txt", "w") as f:
    f.write("\n".join(([" ".join([str(a[0]), str(a[1])]) for a in zip(col1, col2)])))

讀取文件:

fp = open("abc.txt")
content = fp.read();
lines = content.split("\t") #split row by tab spaces to form a list

將輸入行拆分為兩個列表:

l1=[]  #list1 to store col 1
l2=[]  #list2 to store col 2
for i in range(0,len(lines)):
    if(i%2 == 0):
        l2.append(lines[i])
    else:
        l1.append(lines[i])

將列表壓縮成表格組(以后可以將其寫入文件):

for x in list(zip(l1,l2)):
    print(x)

寫入文件:

fp=open("E:/efg.txt",'a')
for x in list(zip(l1,l2)):
    fp.write(('\t'.join(x)))
    fp.write('\n')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM