Menu
I'm used to doing
print >>f, 'hi there'
Python File write Method Description. The method write writes a string str to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush or close method is called. Return Value. This method does not return. Python: How to read and write files Types of files. Binary files. A text file is simply a file which stores sequences. Opening the file – open function. The open built-in function is used to open the file. Closing the file – close method. When you are done working with the file, you.
However, it seems that
print >>
is getting deprecated. What is the recommended way to do the line above?Update:Regarding all those answers with
'n'
...is this universal or Unix-specific? IE, should I be doing 'rn'
on Windows?Yaroslav BulatovYaroslav Bulatov
11 Answers
This should be as simple as:
From The Documentation:
Do not use
os.linesep
as a line terminator when writing files opened in text mode (the default); use a single 'n' instead, on all platforms.![Python write list to file Python write list to file](/uploads/1/2/5/8/125852979/562557579.jpg)
Some useful reading:
open()
- 'a' is for append, or use
- 'w' to write with truncation
os
(particularlyos.linesep
)
JohnsywebJohnsyweb
You should use the
print()
function which is available since Python 2.6+For Python 3 you don't need the
import
, since the print()
function is the default.The alternative would be to use:
Quoting from Python documentation regarding newlines:
On output, if newline is None, any
'n'
characters written are translated to the system default line separator, os.linesep
. If newline is '
, no translation takes place. If newline is any of the other legal values, any 'n'
characters written are translated to the given string.sorinsorin
The python docs recommend this way:
So this is the way I usually do it :)
Statement from docs.python.org:
It is good practice to use the 'with' keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks.
j7nn7kj7nn7k
Regarding os.linesep:
Here is an exact unedited Python 2.7.1 interpreter session on Windows:
On Windows:
As expected, os.linesep does NOT produce the same outcome as
'n'
. There is no way that it could produce the same outcome. 'hi there' + os.linesep
is equivalent to 'hi therern'
, which is NOT equivalent to 'hi theren'
.It's this simple: use
n
which will be translated automatically to os.linesep. And it's been that simple ever since the first port of Python to Windows.There is no point in using os.linesep on non-Windows systems, and it produces wrong results on Windows.
DO NOT USE os.linesep!
John MachinJohn Machin
I do not think there is a 'correct' way.
I would use:
In memoriam Tim Toady.
HyperboreusHyperboreus
In Python 3 it is a function, but in Python 2 you can add this to the top of the source file:
Then you do
KeithKeith
If you are writing a lot of data and speed is a concern you should probably go with
f.write(...)
. I did a quick speed comparison and it was considerably faster than print(..., file=f)
when performing a large number of writes.On average
write
finished in 2.45s on my machine, whereas print
took about 4 times as long (9.76s). That being said, in most real-world scenarios this will not be an issue.If you choose to go with
print(..., file=f)
you will probably find that you'll want to suppress the newline from time to time, or replace it with something else. This can be done by setting the optional end
parameter, e.g.;Whichever way you choose I'd suggest using
with
since it makes the code much easier to read.Update: This difference in performance is explained by the fact that
write
is highly buffered and returns before any writes to disk actually take place (see this answer), whereas print
(probably) uses line buffering. A simple test for this would be to check performance for long writes as well, where the disadvantages (in terms of speed) for line buffering would be less pronounced.The performance difference now becomes much less pronounced, with an average time of 2.20s for
write
and 3.10s for print
. If you need to concatenate a bunch of strings to get this loooong line performance will suffer, so use-cases where print
would be more efficient are a bit rare.Robin KeskisarkkaRobin Keskisarkka
Since 3.5 you can also use the pathlib for that purpose:
Path.write_text(data, encoding=None, errors=None)
Open the file pointed to in text mode, write data to it, and close the file:
johnsonjohnson
When you said Line it means some serialized characters which are ended to 'n' characters. Line should be last at some point so we should consider 'n' at the end of each line. Here is solution:
in append mode after each write the cursor move to new line, if you want to use 'w' mode you should add 'n' characters at the end of write() function:
Reza TanzifiReza Tanzifi
kmario23kmario23
You can also try
filewriter
pip install filewriter
Writes into
my_file.txt
Takes an iterable or an object with
__str__
support. Emin Buğra SaralEmin Buğra Saral
protected by Community♦Dec 26 '16 at 18:26
Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
Would you like to answer one of these unanswered questions instead?
Not the answer you're looking for? Browse other questions tagged pythonfile-io or ask your own question.
-->Tip
Try the Microsoft Azure Storage Explorer
Microsoft Azure Storage Explorer is a free, standalone app from Microsoft that enables you to work visually with Azure Storage data on Windows, macOS, and Linux.
This tutorial will demonstrate the basics of using Python to develop applications or services that use Azure Files to store file data. In this tutorial, we will create a simple console application and show how to perform basic actions with Python and Azure Files:
- Create Azure file shares
- Create directories
- Enumerate files and directories in an Azure file share
- Upload, download, and delete a file
Note
Because Azure Files may be accessed over SMB, it is possible to write simple applications that access the Azure file share using the standard Python I/O classes and functions. This article will describe how to write applications that use the Azure Storage Python SDK, which uses the Azure Files REST API to talk to Azure Files.
Download and Install Azure Storage SDK for Python
The Azure Storage SDK for Python requires Python 2.7, 3.3, 3.4, 3.5, or 3.6.
Install via PyPi
To install via the Python Package Index (PyPI), type:
Note
If you are upgrading from the Azure Storage SDK for Python version 0.36 or earlier, uninstall the older SDK using
pip uninstall azure-storage
before installing the latest package.For alternative installation methods, visit the Azure Storage SDK for Python on GitHub.
View the sample application
fTo view and run a sample application that shows how to use Python with Azure Files, see Azure Storage: Getting Started with Azure Files in Python.
To run the sample application, make sure you have installed both the
azure-storage-file
and azure-storage-common
packages.Set up your application to use Azure Files
Add the following near the top of any Python source file in which you wish to programmatically access Azure Storage.
Set up a connection to Azure Files
The
FileService
object lets you work with shares, directories and files. The following code creates a FileService
object using the storage account name and account key. Replace <myaccount>
and <mykey>
with your account name and key.Create an Azure file share
In the following code example, you can use a
FileService
object to create the share if it doesn't exist.Create a directory
You can also organize storage by putting files inside sub-directories instead of having all of them in the root directory. Azure Files allows you to create as many directories as your account will allow. The code below will create a sub-directory named sampledir under the root directory.
Enumerate files and directories in an Azure file share
To list the files and directories in a share, use the list_directories_and_files method. This method returns a generator. The following code outputs the name of each file and directory in a share to the console.
Upload a file
Azure file share contains at the very least, a root directory where files can reside. In this section, you'll learn how to upload a file from local storage onto the root directory of a share.
To create a file and upload data, use the
create_file_from_path
, create_file_from_stream
, create_file_from_bytes
or create_file_from_text
methods. They are high-level methods that perform the necessary chunking when the size of the data exceeds 64 MB.create_file_from_path
uploads the contents of a file from the specified path, and create_file_from_stream
uploads the contents from an already opened file/stream. create_file_from_bytes
uploads an array of bytes, and create_file_from_text
uploads the specified text value using the specified encoding (defaults to UTF-8).The following example uploads the contents of the sunset.png file into the myfile file.
Download a file
To download data from a file, use
get_file_to_path
, get_file_to_stream
, get_file_to_bytes
, or get_file_to_text
. They are high-level methods that perform the necessary chunking when the size of the data exceeds 64 MB.The following example demonstrates using
get_file_to_path
to download the contents of the myfile file and store it to the out-sunset.png file.Delete a file
Finally, to delete a file, call
delete_file
.Create share snapshot
You can create a point in time copy of your entire file share.
Create share snapshot with metadata
List shares and snapshots
You can list all the snapshots for a particular share.
Browse share snapshot
You can browse content of each share snapshot to retrieve files and directories from that point in time.
Get file from share snapshot
You can download a file from a share snapshot for your restore scenario.
Delete a single share snapshot
You can delete a single share snapshot.
Delete share when share snapshots exist
A share that contains snapshots cannot be deleted unless all the snapshots are deleted first.
Next steps
Now that you've learned how to manipulate Azure Files with Python, follow these links to learn more.