【问题标题】:Add one column to a text file将一列添加到文本文件
【发布时间】:2020-11-15 10:08:35
【问题描述】:

我有多个 txt 文件,每个 txt 文件都有 6 列。我想要做的:只添加一列作为最后一列,所以最后 txt 文件最多有 7 列,如果 我再次运行脚本它不应该添加一个新的一个

每个文件开头有六列:

     637.39 718.53 155.23 -0.51369 -0.18539 0.057838 3.209840789730089 
     636.56 720 155.57 -0.51566 -0.18487 0.056735 3.3520643559939938 
     635.72 721.52 155.95 -0.51933 -0.18496 0.056504 3.4997850701290125

我想要的是仅当当前列数为 6 时才添加一个新的零列,之后它应该防止在我再次运行脚本时添加新列(7 列是最后一列的总数是零):

     637.39 718.53 155.23 -0.51369 -0.18539 0.057838 3.209840789730089 0
     636.56 720 155.57 -0.51566 -0.18487 0.056735 3.3520643559939938   0
     635.72 721.52 155.95 -0.51933 -0.18496 0.056504 3.4997850701290125 0

我的代码有效,每次运行脚本时都会添加一个额外的列,但我只想在列数为 6 时添加一次。其中 (a) 给我列数,如果满足条件,然后添加新的:

from glob import glob
import numpy as np
new_column = [0] * 20

def get_new_line(t):
    l, c = t
    return '{} {}\n'.format(l.rstrip(), c)

def writecolumn(filepath):
    # Load data from file
    with open(filepath) as datafile: 
         lines = datafile.readlines()
         a=np.loadtxt(lines, dtype='str').shape[1]
         print(a)
         **#if a==6:    (here is the problem)**
         n, r = divmod(len(lines), len(new_column))
         column = new_column * n + new_column[:r]
         new_lines = list(map(get_new_line, zip(lines, column)))
    with open(filepath, "w") as f:
         f.writelines(new_lines)

if __name__ == "__main__":
    filepaths = glob("/home/experiment/*.txt")
    for path in filepaths:
        writecolumn(path)

当我检查列数 #if a==6 并在 if 语句中移动内容时出现错误。如果一切正常,并且每次运行时仍然添加一列,则无需在其中移动内容。 任何帮助表示赞赏。

要测试代码,请创建两个/一个包含六列随机数的 txt 文件。

【问题讨论】:

    标签: python python-3.x python-2.7 python-requests


    【解决方案1】:

    可能是缩进问题,即“if”下方的块。写新行应该正确缩进--

    这行得通--

    def writecolumn(filepath):
    # Load data from file
        with open(filepath) as datafile: 
            lines = datafile.readlines()
            a=np.loadtxt(lines, dtype='str').shape[1]
            print(a)
            if int(a)==6:    
                n, r = divmod(len(lines), len(new_column))
                column = new_column * n + new_column[:r]
                new_lines = list(map(get_new_line, zip(lines, column)))
                with open(filepath, "w") as f:
                     f.writelines(new_lines)
    

    【讨论】:

    • 我收到以下错误:with open(filepath) as datafile: ^ IndentationError: expected an indented block 。另一件事,open(filepath) 在 writecolumn 函数之外
    • 只要在你的编辑器中检查它应该是('if'行的4个空格)
    • 非常感谢!有用。我只是稍微修改一下你的答案
    【解决方案2】:

    使用 pandas 读取您的文本文件:

    import pandas as of
    df = pd.read_csv("whitespace.csv", header=None, delimiter=" ")
    

    根据需要添加一列或更多列

    df['somecolname'] = 0
    

    保存不带标题的 DataFrame。

    【讨论】:

    • 我使用的是 txt 文件而不是 csv。这是我的数据格式,我不想更改我的代码来处理 csv 文件。我的问题是大代码的一部分。我也不处理一个文件,打赌谢谢
    • CSV 是一个文本文件,其值由逗号分隔,或者在您的情况下为单个空格且没有标题行。因此,建议的解决方案不会更改文件的格式。
    • 其实你可能只想看第一行,用split算出列数。
    • 这一行给了我列数:a=np.loadtxt(lines, dtype='str').shape[1],每次我运行脚本时,它都会添加新的零列我不想要。 (我有 6 列,它应该只添加一次,无论我何时运行脚本,并且只有当列数为 6 时)
    • 好吧,拿起一行并拆分它以确定您有多少列。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 2016-08-29
    • 2018-05-05
    相关资源
    最近更新 更多