Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, writing an integer to a '.txt' file

Would using the pickle function be the fastest and most robust way to write an integer to a text file?

Here is the syntax I have so far:

import pickle

pickle.dump(obj, file)

If there is a more robust alternative, please feel free to tell me.

My use case is writing an user input:

n=int(input("Enter a number: "))
  • Yes, A human will need to read it and maybe edit it
  • There will be 10 numbers in the file
  • Python may need to read it back later.
like image 882
clickonMe Avatar asked Apr 21 '13 12:04

clickonMe


People also ask

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

To write to a text file in Python, you follow these steps: First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.

How do you write an integer to a file?

We use the getw() and putw() I/O functions to read an integer from a file and write an integer to a file respectively.

Can I write to a file in Python?

To write to a text file in Python, you can use the built-in open function, specifying a mode of w or wt . You can then use the write method on the file object you get back to write to that file. It's best to use a with block when you're opening a file to write to it.


1 Answers

I think it's simpler doing:

number = 1337

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

But it really depends on your use case.

like image 57
Alex Avatar answered Sep 21 '22 05:09

Alex