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

4 Surprising Ways Artificial Intelligence will Empower Consumers

Ever wonder what makes Siri search the items inside the iPhone and on the web by recognizing your voice? How does Google listening work? Artificial Intelligence and data science have already infused in this consumer-oriented generation, but we have not realized it yet. It has been quite a while that natural language processing, speech recognition, and gesture recognition system took over the market with their all new features, but what are the new things in AI that are yet to come? Few amazing transformations are: Retailing sector to become AI-ready Voice Recognition will change the game Search engines to become smarter Machine learning to bring revolutionary changes Recently we got to learn about a verbal spat between Elon Musk and Mark Zuckerberg over the probable risk and opportunities brought by AI . Believe it or not, but we already accustomed to Artificial Intelligence and probably waiting to witness jaw-dropping inventions. Some of AI inventions we have known till yet are: Mach

How to unhide or show folders in mx player list

In this blog post, I tell you about how to Show or Hide folders from MX player list. There are two methods to Show folder from MX Player list. Method 1: Unhide / show folders If you want to temporarily Show / Unhide hidden folder from MX Player list, then go to Settings and untick Recognize .nomedia ".  Method 2: Permanently unhide / show folder: Open memory by any file explorer and I recommend X-Plore, and open the folder that is Hidden and find the file " .nomedia ". If you didn't find it, you should first enable "Show files hidden files that starts with .(dot)". Delete the file and you just need to refresh MX Player list to take changes. Note: MX Player always hide those folders which file " .nomedia " exists.

How to use arrays in Python

Arrays in Python give you a huge amount of flexibility for storing, organizing, and accessing data. This is crucial, not least because of Python’s popularity for use in data science. But what precisely is an array? And how do you use arrays in Python? Also read: How to use dictionaries in Python Read on, and we’ll shed some light on the matter. What is an array? An array is a way to store multiple values in a single variable. That means that you can use a single “reference” in order to access your data. A list is also an example of a variable that stores multiple values, but has some slight differences. When using lists in Python, you store a series of values each with a numbered index. For example, this is how you would create a list of fruits in Python: fruits = [“apple”, “orange”, “pear”, “nectarine”] If we then say: print(fruits[3]) We will see “nectarine” appear on the screen (the first entry is stored as “0”). Also read: How to use lists in Python This is not an