Best method in writing a list to a text file in python?

↘锁芯ラ 提交于 2020-01-06 06:25:38

问题


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)

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)

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

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

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() 

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

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

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

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

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.

Hi All

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?


回答1:


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]))



回答2:


So if i understand the filestructure you want correctly:

you want each line to have 7 numbers in order "t z y x Rz Ry Rx" with space between them.

First you need to go through first element of all lists, than through second, etc...

To do so best may be zip (documentation)

with open(filename, 'w') as f:  # We open file for writing
    for line in zip(t, z, y, x, Rz, Ry, Rx):
        line = [str(i) for i in line]  # convert to strings
        f.write(' '.join(line) + "\n")  # joins space and ends the line

EDIT:

Ok, so if I now understand the format, the following shoud help:

with open('x.txt', 'w') as f:
    f.write('\n'.join([str(i) for i in x]) + '\n')  # omit "+ '\n'" if you don't want newline at the end of the file.

Repeate for each variable.

EDIT 2:

My explanation for why your methods don't work:

method 1

It's just how csv writer's writerows work

method 2

you are doing for each item in x, where x is list, not file you can write to. Corrected code:

with open('x.txt', 'w') as f:
    for item in x:
        f.write(str(item) + '\n')

note that '%s\n' can't work as item is int and s is for string, f.write('%d\n' % item) shoud work

method 3

str(x) formats list to the form you see it in file and you just write that into the file. The formating can be seen by doing print(str(x))

method 4

again same as in method 2

method 5

Similar to method 2. You don't define number anywhere. For it to work use:

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


来源:https://stackoverflow.com/questions/48362364/best-method-in-writing-a-list-to-a-text-file-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!