簡體   English   中英

如何使用 python 刪除.dat 文件中的行之間的空間?

[英]How to remove space between rows in .dat files using python?

我正在處理一個數據文件,它只有兩列:

 1 100
 2 200
 3 300
 4 400
 5 500

 6 600
 7 700
 8 800
 9 900
10 1000

11 1100
12 1200
13 1300
.
.
. 

該文件為.dat格式,我使用np.loadtxt方法加載。 我想刪除隨機出現的行之間的空格。 我不能手動完成,因為它們太多了。 所以,我想知道是否可以使用 python 中的任何方法來執行此任務。

請對此提出建議。
謝謝!

您最好的選擇是使用具有特定配置的pandas.read_csv()

>>> import pandas as pd
>>> df = pd.read_csv("<your_dat_file>", delimiter=" ", header=None, skipinitialspace=True)
>>> df
     0     1
0    1   100
1    2   200
2    3   300
3    4   400
4    5   500
5    6   600
6    7   700
7    8   800
8    9   900
9   10  1000
10  11  1100
11  12  1200
12  13  1300

我實際上將此視為基本 Python 問題,因此建議:

import re

with open("data_file.txt", "r") as fin, open("data_file_out.txt", "w") as fout:
    for line in fin.readlines():
        if re.search(r'\S', line):
            fout.write(line)

上面生成的文件data_file_out.txt應該包含 sams 內容作為您的當前文件,刪除空行(“空”在這里定義為沒有內容或只有空白字符的行)。

暫無
暫無

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

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