[英]Modify a table in .txt file using python
我有一個 .txt 文件,其中包含如下組織的一組數據:
(id1) (name1) (x coordinate1) (y coordinate1) (value1)
(id2) (name2) (x coordinate2) (y coordinate2) (value2)
(id3) (name3) (x coordinate3) (y coordinate3) (value3)
.....
現在我想將所有(名稱)從第 2 列移到第 4 列。我寫的代碼是這樣的:
with open("C:\\path\\to\\input\\file.txt","r") as f:
rows = list(f)
table = [["."],["."],["."],["."],["."],["."]]*len(rows)
for i in range(len(rows)):
row = rows[i].split(" ")
table[6*i] = row[0]+" "
table[6*i+1] = row[2]+" "
table[6*i+2] = row[3]+" "
table[6*i+3] = row[1]+" "
table[6*i+4] = row[4]
table[6*i+5] = "\n"
with open("C:\\path\\to\\output\\file.txt","w") as o:
o.writelines(table)
它執行任務,但輸出在每行之后包含一個空行。 我已經嘗試了幾個小時來擺脫它們,但我無法弄清楚如何獲得正確的輸出。 錯誤的輸出是這樣的:
(id1) (x coordinate1) (y coordinate1) (name1) (value1)
(id2) (x coordinate2) (y coordinate2) (name2) (value2)
(id3) (x coordinate3) (y coordinate3) (name3) (value3)
.....
您正在添加換行符,請嘗試刪除此行:
table[6*i+5] = "\n"
由於您要提取的文件有換行符,因此它們會自動包含在列表中的最后一項中。
編輯:您的源文件可能有點不穩定,您也可以將最后一行更改為:
table[6*i+5] = ""
歡迎來到 StackOverflow!
當您從文件中讀取數據時,新行出現在數據中,因此,當您編寫操作然后在另一個文件中重寫數據時,它會自動換行。 因此無需自己手動添加新行,因為這只會添加額外的不必要的新行(這是我們面臨的問題)。
所以你必須刪除這一行 - table[6*i+5] = "\n"
。 我希望這可以解決您的問題。
如前所述,您正在為每一行添加一個換行符,但您的第 4 列已經包含一個換行符,導致 2 個換行符。
但是,您的代碼還有另一個問題。 file.writelines
需要一個字符串列表,通常在每個字符串的末尾都有一個換行符。 但是您創建了一個表,它是一長串列表,每個列表包含 1 個字符串:
table = [["."],["."],["."],["."],["."],["."]]*len(rows)
然后,您將這些子列表一一替換為字符串:
table[6*i] = row[0]+" " # etc.
如果沒有替換任何內容,則writelines
將引發錯誤,因為存在一個需要字符串的列表。 所以你需要做一些額外的調整來讓你現有的代碼工作:
with open("input.txt") as f:
rows = list(f)
table = ["", "", "", "", ""]*len(rows)
for i in range(len(rows)):
row = rows[i].split(" ")
table[5*i] = row[0]+" "
table[5*i+1] = row[2]+" "
table[5*i+2] = row[3]+" "
table[5*i+3] = row[1]+" "
table[5*i+4] = row[4]
with open("output.txt","w") as o:
o.writelines(table)
然而,這樣做的更好方法是一次構建表一行,如下所示:
with open("input.txt") as f:
table = []
for row in f:
row = row.strip().split(" ") # strip removes any line breaks / extra spaces
table.append([row[0], row[2], row[3], row[1], row[4]])
with open("output.txt","w") as o:
o.writelines(" ".join(row) + "\n" for row in table)
更好的是,使用為此設計的csv
模塊,它將自動處理換行符:
import csv
with open("input.txt") as in_file, open("output.txt", "w", newline="") as out_file:
writer = csv.writer(out_file, delimiter=" ")
for row in csv.reader(in_file, delimiter=" "):
writer.writerow([row[0], row[2], row[3], row[1], row[4]])
或熊貓:
import pandas as pd
pd.read_csv("input.txt", sep=" ", header=None)[[0, 2, 3, 1, 4]] \
.to_csv("output.txt", sep=" ", header=False, index=False)
Pitty 你需要使用 Python。 您可以在命令行中執行此操作(假設您的數據位於文件data.txt
中):
sed -e 's/) (/);(/g' data.txt | awk -F ";" '{print $1 ";" $3 ";" $4 ";" $5 ";" $2}' | sed -e 's/;/ /g'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.