python - 在 python 中将列表写入文本文件的最佳方法?

标签 python text spyder

import pandas
import sys
import os
import csv
import string

f=open(myfile,"r")
lines=f.readlines()
x=[]

for i in lines:

    x.append(i.split()[3]);


f.close()

if not os.path.exists(path):        
    os.chdir(subfolder)

方法 1:此方法有效,但会在列中打印带有分隔数字的数字,如下图所示:。 output

with open('x.txt', 'w') as f:
     writer = csv.writer(f, delimiter='\n')
     writer.writerows(x)

方法 2:此方法给出错误:“list”对象没有属性“write”

#for item in x:
#  x.write("%s\n" % item)

方法 3:这个方法有效,但将所有逗号写在一行中,而我需要一列数字

#file = open("x.txt","w")
# 
#file.write(str(x)) 
# 
# 
#file.close() 

方法 4:错误:“str”对象没有属性“write”

for i in x:
    i.write(i, '\n')

方法 5:错误:名称“编号”未定义

with open('x.txt', 'w') as f:
  f.write('%d' % number)

我对这些错误感到沮丧,我想使用 python 来节省时间,我在调试上浪费了所有时间,现在我几乎即将完成它。我将感谢您的关注。

大家好

我有一个包含 7 列的文本文件,我需要将每一列数字写入一个单独的文本文件。具有许多小数位的数字。所以我试图从 python 中的列表写入文本文件,如您所见,每个相应列表的名称与其应写入的文本文件相同。 但尽管尝试了互联网上的几个现有示例,但我没有成功,而且我不知道错误的原因。 为什么不一次彻底澄清呢?

最佳答案

既然你要导入 pandas,为什么不也使用它呢。

data = pd.read_table(myfile, header=None, sep='\s+')
data.columns = 't','x','y','z','Rx','Ry','Rz'

for column in data:
    with open(column + ".txt", "w") as ofile:
        ofile.write(' '.join(str(i) for i in data[column]))

关于python - 在 python 中将列表写入文本文件的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48362364/

相关文章:

Python 批量追加到特定类型的文件 - 在单个目录中

python - pymongo+update 抛出 $pull

python - 如何让 python 程序在每次发生事情时检查一个值?

python - 使用 Cron 运行在 Spyder IDE 中编写的 python 脚本

python - 我们如何让 Spyder 在发生错误后暂停执行?

javascript - 如何让 JavaScript 和 Python 协同工作?

python - 部署 Python Azure 函数时中央目录损坏

text - TinyMCE:如何禁用代码重写?

c++ - DirectWrite 对齐文本中心

python - 适用于 Windows 10 的 Anaconda (Python 2.7) 出现内核错误。Spyder IDE 控制台错误