在python中将列表写入文本文件的最佳方法? [英] Best method in writing a list to a text file in python?

查看:71
本文介绍了在python中将列表写入文本文件的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:此方法有效,但如您在此处的图像中看到的那样,在列中打印带有分隔数字的数字:.输出

method 1 : this one works, but prints the numbers with separated digits in columns as you see in the image here : .output

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

方法 2:这个方法给出了错误:'list' 对象没有属性 'write'

method 2 : this one gives the error : 'list' object has no attribute 'write'

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

方法 3:此方法有效,但在一行中写入所有逗号的列表,而我需要一列数字

method 3 : this one works, but writes the list with all commas in one row, while I need a column of numbers

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

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

method 4 : Error : 'str' object has no attribute 'write'

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

方法 5 : 错误 : name 'number' 未定义

mthod 5 : Error : name 'number' is not defined

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

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

I am frustrated with these errors, I wanted to use python to save my time, I wasted all that time in debugging and now I am almost at the brink of finishing it. I will appreciate your attention.

大家好

我有一个包含 7 列的文本文件,我需要将每一列数字写入一个单独的文本文件.带有许多十进制数字的数字.所以我试图从python中的列表写入文本文件,如您所见,每个对应列表的名称与它应该写入的文本文件相同.但是尽管尝试了互联网上的几个现有示例,但我并没有成功,而且我不知道错误的原因.为什么不一劳永逸地澄清一下?

I have a text file that contains 7 columns and I need to write each column of numbers to a separate text file. numbers with many decimal digits. So I am trying to write to a text file from a list in python, as you see, the name of each corresponding list is the same as the text file it should be written to. but I am not succeeding despite having tried several existing examples from the internet, and I don't know the reason of the errors. Why not once for all clarify it?

推荐答案

既然你在导入 pandas,那你为什么不也使用它.

Since you are importing pandas, why don't you use it, too.

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中将列表写入文本文件的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆