Write object to text file python

I would like to create a "metadata" file for several Python objects I have built and was wondering if there was an elegant way to write a subset of these attributes to a .txt file. Ideally, the .txt file would have the following formatting:

object.Name = thisistheobjectname object.Value = thisistheobjectvalue etc...

martineau

115k25 gold badges160 silver badges284 bronze badges

asked Jul 8, 2015 at 14:43

4

If your goal is to reuse this object later on, then don't reinvent the wheel and use pickle. But if your goal is to just get objects variables in a nice looking txt file then you can leverage __dict__ of the object

You can ether store it in JSON or convert it to what ever works for you:

For example:

import json

class Foo[object]:
  def __init__[self, name, value]:
    self.name = name
    self.value = value

myfoo = Foo['abc', 'xyz']
with open['foo.txt', 'w'] as f:
  f.write[' '.join[["myfoo.%s = %s" % [k,v] for k,v in myfoo.__dict__.iteritems[]]]]

Will result in something like:

myfoo.name = abc myfoo.value = xyz

answered Jul 8, 2015 at 14:52

VorVor

31.4k42 gold badges132 silver badges189 bronze badges

1

If you are looking for something simple, you can use this for your example above.

import sys
class Foo[object]:
    bar = 'hello'
    baz = 'world'

f = Foo[]
print "\n".join[["`%s.Name=%s %s.Value=%s`" % [f.__class__.__name__, name, f.__class__.__name__, getattr[f, name]] for name in dir[f] if not name.startswith["__"]]]

will give

`Foo.Name=bar Foo.Value=hello`
`Foo.Name=baz Foo.Value=world`

For more complex serialization you are better off using pickle

answered Jul 8, 2015 at 15:08

vHalaharvivHalaharvi

1751 silver badge9 bronze badges

  • Writing to a file without “with”
  • Adding the newline character
  • Write vs writeline
  • Append to a text file

To write to a text file in Python, you have to use the open[] and write[] functions. The open[] function takes two parameters: file name and file access mode. The returned value of open[] is the file object.

The file object is a mediator that can be used by the write[] function to pass value to a file.

with open['D:/text_file.txt', 'w'] as f:
    f.write['Just a simple text.']

If the file doesn’t exist, it’s created. If it’s already present, it’s overwritten.

Locate and open the file to see that the file is present and the text is written to a file.

Contents

  • 1 Writing to a file without “with”
  • 2 Adding the newline character
  • 3 Write vs writeline
  • 4 Append to a text file

Writing to a file without “with”

When you use the “with” statement, the object is automatically closed if it leaves the scope.

with open['D:/text_file.txt', 'w'] as f:
    f.write['Just a simple text.']
    print[f.closed]
print[f.closed]

The first print function returns False because we are still within the “with” scope therefore the file is not closed. When we leave the scope the function returns True.

False
True

You can also create code that writes to a file without using “with”.

f = open['D:/text_file.txt', 'w']
f.write['Just a simple text without "with".']
print[f.closed]
f.close[]
print[f.closed]

This code creates and opens a file. Next, it writes the string to the file with the write[] function. It doesn’t close the file object at the end – you have to do it explicitly. To prove it, there are two print functions. If you run the code the function will return these values:

False
True

The first value returns False because the file object is not closed, the second value is True because the close method is executed just before the second print.

Adding the newline character

So far we’ve used only one write[] function. Let’s add the second function with additional text.

with open['D:/text_file.txt', 'w'] as f:
    f.write['First text.']
    f.write['Second text.']

The is no newline [\n] character inside the text, therefore the second text is written just after the first one.

First text.Second text.

If you want to write one text after another, you have to add this character at the end of the first line.

with open['D:/text_file.txt', 'w'] as f:
    f.write['First text.\n']
    f.write['Second text.\n']

The newline character is added just after the first string, moving the cursor to the new line. The second string is written and new lines are added just after that. It’s not necessary in this case, as there is no additional text after that, but it places the cursor in a new line, so the next string will be placed correctly.

First text.
Second text.

Write vs writeline

The write[] function takes a string as a parameter. The writeline[] function can also take a single string, but you can additionally put there a list of strings.

my_list = ['First text.\n', 'Second text.\n']

with open['D:/text_file.txt', 'w'] as f:
    f.writelines[my_list]

This code will give us the same result as the previous one.

First text.
Second text.

If you want to pass a list of strings to write[], you can do it using the for loop and write them line by line.

my_list = ['First text.\n', 'Second text.\n']

with open['D:/text_file.txt', 'w'] as f:
    for line in my_list:
        f.writelines[line]

Another, more compact way to do it, is to use the join[] function. This function merges all strings from the list using the separator.

my_list = ['First text.\n', 'Second text.\n']

with open['D:/text_file.txt', 'w'] as f:
    f.write[''.join[my_list]]

In this case, we shouldn’t use the new line separator with the join[] function, because there are newline characters at the end of each list element.

If we have a lot of strings inside a list, a better way would be to add the separator not within the list elements, but with the join[] function.

my_list = ['First text.', 'Second text.']

with open['D:/text_file.txt', 'w'] as f:
    f.write['\n'.join[my_list]]

Append to a text file

When it comes to accessing the file, there are six access modes. We are going to use only two as the other ones are used for reading files. We have used the ‘w’ access file for writing, not we will take a closer look at the append ‘a’ access mode.

Mode Description
Write only [w] Open file for writing. The handle is positioned at the beginning of the file. Creates a new file if the file doesn’t exist. For an existing file, the data is overwritten.
Append only [a] Open file for writing. The handle is positioned at the end of the file. The file is created if it doesn’t exist.

The only modification we have to do, to open the file in append mode, is to change the letter ‘w’ to ‘a’.

Delete the file and run the code again.

with open['D:/text_file.txt', 'a'] as f:
    f.write['First text.\n']
    f.writelines['Second text.\n']

If you run the code for the first time, it’s going to return the same result as before. But if you run it for the second time, it will move the cursor to the end of the file and write two lines there.

First text.
Second text.
First text.
Second text.

How do you write data into a file in Python?

You can write to a file in Python using the open[] function . You must specify either “w” or “a” as a parameter to write to a file. “w” overwrites the existing content of a file. “a” appends content to a file.

How do you create a text file in Python?

For creating a new text file, you use one of the following modes:.
'w' – open a file for writing. If the file doesn't exist, the open[] function creates a new file. ... .
'x' – open a file for exclusive creation. If the file exists, the open[] function raises an error [ FileExistsError ]..

How do you write a list to a text file in Python?

Use file..
a_list = ["abc", "def", "ghi"].
textfile = open["a_file.txt", "w"].
for element in a_list:.
textfile. write[element + "\n"].
textfile. close[].

How do you write a string to a text file in Python?

Python – Write String to Text File Open the text file in write mode using open[] function. The function returns a file object. Call write[] function on the file object, and pass the string to write[] function as argument. Once all the writing is done, close the file using close[] function.

Chủ Đề