0

I have a list that looks like this

list_geo = [[5], ['Optimized energy: -39.726863484331 E_h'],
    ['C\t', '-1.795202\t', ' 0.193849\t', ' 0.019437'],
    ['H\t', '-0.728046\t', '0.337237\t', ' 0.135687'],
    ['H\t', '-2.044433\t', '-0.840614\t', ' 0.220592'],
    ['H\t', '-2.085087\t', ' 0.444715\t', '-0.993886'],
    ['H\t', '-2.323267\t', ' 0.834105\t', ' 0.714902']]

I want to write this to file outputfile, and I tried to use

with open(outputfile, "w") as output_file:
    output_file.write(list_geo)

But this does not work. Joining list_geo also does not work. How can I save this?

smci
  • 32,567
  • 20
  • 113
  • 146
Yoda
  • 574
  • 1
  • 9
  • 21
  • and how should look the final text? – RomanPerekhrest Dec 16 '17 at 11:43
  • 2
    Never say *"this does not work"*. Say why. Include the error/exception. In your case because you can't pass `file.write()` a list, it gives `TypeError: expected a string or other character buffer object`. So clearly you need to figure out how to make a string out of your list. There are already [22 questions](https://stackoverflow.com/search?q=%5Bpython%5D+file+TypeError%3A+expected+a+string+or+other+character+buffer+object) on that, this is a duplicate. – smci Dec 16 '17 at 12:01
  • Duplicate of [**Write list variable to file **](https://stackoverflow.com/questions/43701610/write-list-variable-to-file), also [Writing list of basic variables to text file](https://stackoverflow.com/questions/46934333/writing-list-of-basic-variables-to-text-file) ... – smci Dec 16 '17 at 12:05
  • People, 22 questions on the same topic is a mess. Time to canonicalize. See [How best to canonicalize all the “Python write list(/variable/data structure) to file”-type questions?](https://meta.stackoverflow.com/questions/360765/how-best-to-canonicalize-all-the-python-write-list-variable-data-structure-to) – smci Dec 16 '17 at 12:18
  • 1
    Here's the answer to the question you didn't ask but should have. Looks like your data came from a tab-separated file, you just read it in as-is, without even stripping the `\t` separators, and stored string representations of numbers (`'-0.840614\t'`) with whitespace attached. Rather than storing the actual numbers. Just use [pandas `read.csv()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html) instead. It will make your life much easier. When you want to write out the data, read about number formatting. – smci Dec 16 '17 at 12:26
  • where do you have these strings from? – hansaplast Dec 16 '17 at 12:28
  • @hansaplast: I just guessed they came from a read.csv of a Tab-Separated File done badly. And I suggested a better solution that avoids all these formatting woes. – smci Dec 16 '17 at 12:31
  • Possible duplicate of [Writing a list to a file with Python](https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python) – CristiFati Dec 27 '17 at 10:49

3 Answers3

1

You need to use for loop

with open("path /of/op/file.txt", "w") as output_file:
   for value in list_geo:
       output_file.write(str(value))
sam
  • 25
  • 7
0

I guess want to write every sublist of your list as one line.

Then this is what you need:

list_geo = [[5], ['Optimized energy: -39.726863484331 E_h'],
    ['C\t', '-1.795202\t', '0.193849\t', '0.019437'],
    ['H\t', '-0.728046\t', '0.337237\t', '0.135687'],
    ['H\t', '-2.044433\t', '-0.840614\t', '0.220592'],
    ['H\t', '-2.085087\t', '0.444715\t', '-0.993886'],
    ['H\t', '-2.323267\t', '0.834105\t', '0.714902']]

with open("file.txt", "w") as output_file:
   for line in list_geo:
       output_file.write("".join([str(i) for i in line]))
       output_file.write("\n")

Content of file.txt after running the script:

5
Optimized energy: -39.726863484331 E_h
C       -1.795202       0.193849       0.019437
H       -0.728046       0.337237       0.135687
H       -2.044433       -0.840614      0.220592
H       -2.085087       0.444715       -0.993886
H       -2.323267       0.834105       0.714902

Explanation:

  • "".join() takes a list of strings and just concatenates them together without spaces in between
  • [str(i) for i in line] converts every element in the list into string (needed only because you have the [5] as the first sublist in your list)

Is there a way to preserve the extra space in positive number?

If you want to add formatting to your lines you better have the values as real numbers first, i.e. instead of ['C\t', '-1.795202\t', ' 0.193849\t', ' 0.019437'] you'd need ['C', -1.795202, 0.193849, 0.019437] and then format them with e.g. "{}\t{:>9f}\t{:>9f}\t{:>9f}\n".format(*line).

If you somehow just get this list from a dirty source you cannot change, then you'd need to preprocess the line somehow, e.g. like this:

list_geo = [[5], ['Optimized energy: -39.726863484331 E_h'],
    ['C\t', '-1.795202\t', '0.193849\t', '0.019437'],
    ['H\t', '-0.728046\t', '0.337237\t', '0.135687'],
    ['H\t', '-2.044433\t', '-0.840614\t', '0.220592'],
    ['H\t', '-2.085087\t', '0.444715\t', '-0.993886'],
    ['H\t', '-2.323267\t', '0.834105\t', '0.714902']]

with open("file.txt", "w") as output_file:
   for line in list_geo:
        if len(line) == 4:
            # treat first element as string, convert rest to float
            line = [el.strip() if i == 0 else float(el) for i,el in enumerate(line)]
            line_formatted = "{}\t{:>9f}\t{:>9f}\t{:>9f}\n".format(*line)
            output_file.write(line_formatted)
        else:
            output_file.write("".join([str(i).strip(" ") for i in line]))
            output_file.write("\n")

Which results in:

5
Optimized energy: -39.726863484331 E_h
C       -1.795202        0.193849        0.019437
H       -0.728046        0.337237        0.135687
H       -2.044433       -0.840614        0.220592
H       -2.085087        0.444715       -0.993886
H       -2.323267        0.834105        0.714902
hansaplast
  • 11,007
  • 2
  • 61
  • 75
  • Is there a way to preserve the extra space in positive number? – Yoda Dec 16 '17 at 12:17
  • where? In the first line? What extra space? – hansaplast Dec 16 '17 at 12:18
  • ah I see, they are not evenly aligned. That's because some of your numbers have space in and some don't. Wait, I'll add this – hansaplast Dec 16 '17 at 12:20
  • 1
    @Yoda: you're asking about string formatting of numbers now. If you want to write them formatted, you really shouldn't be storing a list of string representations of the numbers (`'-0.840614\t'`) with trailing whitespace, you should store a list of the numbers themselves. And apply the correct formatting when you write them. – smci Dec 16 '17 at 12:22
  • @Yoda: I now fixed the indentation by adding a space into the array, as fixing the spacing in python turned out very messy and hacky – hansaplast Dec 16 '17 at 12:27
  • @Yoda: now I added a preprocess step. But really, you should answer the questions people are posing here, otherwise you a) won't get the needed help and b) waste other peoples time because they are just guessing – hansaplast Dec 16 '17 at 13:11
-1

You can't write a list directly to file, but you can write a string/stream of characters.

Convert your list into a string and then write the string to the file

data = ['1','2'] 
data_string = ','.join(data) # create string and then store

with open('f.txt','w') as f:
        f.write(data)
smci
  • 32,567
  • 20
  • 113
  • 146
babygame0ver
  • 447
  • 4
  • 16
  • That is not a list of lists. Besides if you have a comma in data then simply doing joins with one character will brake your data. – Nux Oct 23 '22 at 19:18