【问题标题】:Import .txt file with commas and no spaces between numbers导入带有逗号且数字之间没有空格的 .txt 文件
【发布时间】:2019-08-04 04:58:53
【问题描述】:

我目前正在尝试导入 .txt 文件。我通常喜欢代码:

GID = np.genfromtxt("C:\\Users\\Downloads\\Python\\myfile.txt")
q= GID[:,][:,0]

但是我什至尝试过:

with open('C:\\Users\\Downloads\\Python\\myfile.txt', 'r') as myfile:
UV = myfile.read().replace('\n', '')
UV = UV.replace(',', ' ')

我目前遇到的问题是我尝试导入的文件有超过 1000 行应该有两列数字。但是,它用逗号分隔两列,没有空格,如下所示:

1234.56,-7.89
987.65,43.21

如果我尝试使用 genfromtxt 命令导入值,它只会将所有内容都导入为“nan”。如果我尝试使用“with open”命令导入值并用空格替换所有逗号,我会失去两列和超过 1000 行的格式。

有什么建议吗?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    它似乎是一个逗号分隔值文件 (csv)。使用python csv module或者pandasread_csv函数...或者如果你想要genfromtxt,你可以使用delimiter参数:

    genfromtxt('my_file.txt', delimiter=',')
    

    【讨论】:

    • 这行得通!哇,这太简单了。感谢您的帮助。
    【解决方案2】:
    with open('C:\\Users\\Downloads\\Python\\myfile.txt', 'r') as myfile:
        for UV in myfile.read().replace(',', ' ').split('\n'):
            print(UV)
    

    你必须拆分 file.read('\n') 而不是替换新行:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      • 2020-09-22
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多