Skip to main content

How to write to a file in Python – Txt, Docx, CSV, and more!

How to write to a file in Python

Writing to files is one of the most important things you will learn in any new programming language. This allows you to save user data for future reference, to manipulate large data sets, or to build useful tools like word processors and spreadsheets. Let’s find out how to write to a file in Python!

How to write to a file in Python – .txt files

The simplest way to write to a file in Python, is to create a new text file. This will allow you to store any string to retrieve later.

To do this, you first open the file, then add the content you want, and then close the file to finish.

myFile = open("NewFile.txt", "w+")

myFile.write("Hello World!")

myFile.close()

In this example, we have opened a new file, written the words “Hello World!” and then closed the file.

The “w+” tells Python that we are writing to a new file. If the file already exists, then that file is overwritten. If the file doesn’t already exist, then it will be created.

But what if you want to append (add) to a file that already exists? In this case, you simply swap the “w+” for an “a+”.

You can learn more useful tricks in a previous article:

This will show you how to delete and move files too!

To display the contents of the file, just use the following two lines:

myFile = open("NewFile.txt", "r")

fileContents == myFile.read()

How to write to other types of file

But what if you have another type of file you want to work with, other than a text file? What if you want to create a new spreadsheet file? Or a new Word document?

In many cases, you simply need to learn the formatting used by a particular file-type and then emulate this. For example, CSV files are used to store spreadsheets. The name “CSV” actually refers to the way this formatting works: “Comma-Separated Values.”

In short, each line represents a row in a database and contains a series of values separated by commas. Each comma represents the start of a new column or cell!

You can, therefore, save a bunch of data using the exact same method you used to create your text file, but ensure to insert commas and new-lines in the right place. If you then save the file as “.CSV” then it will open in Excel when you click on it!

The same goes for many other types of file. For example, you could create a HTML file this way by using triangular tags to define headers, bold text, and other basic formatting!

Many developers will create their own formats for storing data specific to their creations. Now you know how to write to a file in Python regardless of the type of file!

Learn more about CSV files in Python here:

How to write to a file in Python with modules

Of course, some files are going to contain more complex formatting than others. For example, if you want to write a .Doc file in Python, you’ll come unstuck! Open a Word document in a text editor and you’ll see that Microsoft uses a lot of confusing formatting and annotation to define the layout and add additional information.

This is where modules come in!

First, install the module you want via pip. You can do this by using the following command:

pip install python doc-x

If you are running from a command line in Windows, try:

python –m pip install doc-x

Now in your Python code you can do the following:

import docx

mydoc = docx.Document()

mydoc.add_paragraph("Hello World!")

mydoc.save("D:/NewHelloDoc.docx")

This will write “Hello World!” to a document and then close it! You can also do some other, more complex formatting:

mydoc.add_heading("Header 1", 0)

mydoc.add_heading("Header 2", 1)

mydoc.add_heading("Header 3", 2)

mydoc.add_picture("D:/MyPicture.jpg", width=docx.shared.Inches(5), height=docx.shared.Inches(7))

Regardless of the type of file you want to work with, you’ll almost always find a module that can handle it for you. These are usually free to use and come with documentation you can route through! That’s just another of the amazing things about coding in Python!


And that is how to write to a file in Python! If you’re enjoying learning Python, then why not take your education to the next level? We’ve compiled a list of the best online Python courses where you can find some amazing discounts. Check it out!



source https://www.androidauthority.com/how-to-write-to-a-file-in-python-1141195/

Comments

Popular posts from this blog

5 tips to Voice Speech Recognition in Android Marshmallow

Android Marshmallow landed on our Android devices. The opportunity for us to offer a small compilation of tricks to try immediately. The latest version of the Google OS starts (very gently, unhurriedly) to be offered on other devices as Nexus. You will find on Android TM, in the coming weeks, a compilation of the best tips for Android 6.0 Marshmallow. It starts slowly with a video featuring the 10 essential tips & tricks of this new version of the little green robot OS. To continue, we offer a selection of five "tricks" on the management of the battery on Android 6.0 Marshmallow. To enjoy longer your newly updated mobile. Follow the guide. then continue with 5 tips to tame the super-assistant Google Now on Tap. Here you will find 5 "tips" to manage in the best way your applications. We then discuss the quick tips to navigate more easily on this version of the Google OS. We enchanters with features focused on safety and the protection of personal data. We co...

Energy Android TV Play turns your TV into a Smart TV

ENERGY SISTEM Android Energy TV Play, you have a smart TV with Android operating system allows you to convert any traditional TV has announced the launch of a new product. Energy Android TV Play can be connected to the TV to enjoy f the size of a flash drive, a smart phone, a tablet and a computer unconsolidated is a lightweight device. System 1.6 GHz, DDR3 1GB of RAM and a dual-core processor can be expanded using external USB devices, which is the internal memory of 8 GB. It also integrates WiFi and a USB port for connecting external devices. One of its outstanding features, it is easily connected to the TV screen by screen cast application to display the contents of any terminal, making any phone or tablet is synchronized with iOS or Android. All ENERGY SISTEM products one click In addition, through streaming media service applications, images, video or other multimedia content, and game play is the ability to share. With integrated WiFi, the device you want from t...

How to run Python apps on any platform

Credit: Adam Sinicki / Android Authority Want to know how to run Python? It sounds simple, but it can actually be tricky to figure this out. In this post, we’ll discuss how to test your Python code, as well as how to run Python in other contexts: online for example, or as a packaged app. Sometimes, the thing holding you back from learning to code can be extremely simple. I remember wanting to learn to program when I was younger – or learning to take what I’d learned from BASIC on the ZX Spectrum and apply that to a modern environment. My problem? I didn’t know “where” to program. Once I understood C# or Java, where would I enter the code and how would I run it? And whenever I asked someone, they would look at me blankly. What kind of a question is that? Thing is, I had never needed an IDE or an interpreter before. Machines like the ZX Spectrum and Tatung Einstein (any other Einstein users out there?) simply booted up with a prompt to code into! Many people have a similar iss...