How to use python write a text

5 Minutes Quickly Learn to Write a File in Python

Through the following tutorial, you will learn how to write to a file in Python. There is also a video tutorial that is easy to understand.

Python is Simple to use.

The brief tutorial is going to show you how to use Python to write different types of file objects. For example, Python writes to a text file, CSV file, JSON file, excel file.

1. Python How to Write a Text File

Python’s built-in open() function that opens the file and returns a corresponding file object. It’s simple.

Write a file use Python

1.1 Write a string to a text

Python write a string to a text is simple, copying the following code, and change it to fix your code.

file_name = "hello.txt"
file_content = "Life is short, I use Python."

with open(file_name, "w") as f:
    f.write(file_content)

Then, run it, you will get a file that named hello.txt. You can change the variable file_name, file_content to become what you want.

1.2 Write a list to a text

If you want to write to a list object to a text file directly in Python, you will get a TypeError: write() argument must be str, not list.

file_name = "hello.txt"
file_content = ["Apple", "Pear", "Banana"]

with open(file_name, "w") as f:
    f.write(file_content)
Write a file use Python

As we mentioned above, you will get TypeError. So, you should make sure that you are writing a string type to text.

file_name = "hello.txt"
file_content = ["Apple", "Pear", "Banana"]
file_content_str = str(file_content)

with open(file_name, "w") as f:
    f.write(file_content_str)
Write a file use Python

When the file_content convert a string type, we can write it to a text file object.

Congratulations! You have successfully writed a list to text.

1.3 Write a dictionary to a text

You can only write a string to a file. If you want to write a dictionary object, you either need to convert it into string or serialize it.

The way to convert it into string:

file_content = {"name": "Jaxon", "age": 18}
file_content_str = str(file_content)

with open("hello.txt", "w") as f:
    f.write(file_content_str)
Write a file use Python

In case of serialization:

import json

file_content = {"name": "Jaxon", "age": 18}

with open("hello.txt", "w") as f:
    f.write(json.dumps(file_content))
Write a file use Python

1.4 Write a new line to a text file

Writing string to a file  on a new line every time, you can  use “\n”

file_name = "hello.txt"
file_content = "Hei, Boy!\n"
file_content_new = "Life is short, I use Python.\n"

with open(file_name, "w") as f:
    f.write(file_content)
    f.write(file_content_new)
Write a file use Python

2. Python How to Write to a CSV File

There is a built-in module called csv. Its csv.writer function will help you create a CSV file. Here is an example of how to use the csv.writer function:

import csv

fruits_list = ["Apple", "Banana", "Pear"]

with open("fruits.csv", "w") as f:
    csv_writer = csv.writer(f)
    csv_writer.writerow(fruits_list)
Write a file use Python
import pandas as pd

fruits_list = ["Apple", "Banana", "Pear"]

df = pd.DataFrame(fruits_list)
df.T.to_csv("fruits.csv", index=False, header=False)

fruits_list_new = ["Grape", "Avacado", "Apricot"]
df_new = pd.DataFrame(fruits_list_new)
df_new.T.to_csv("fruits.csv", mode="a", index=False, header=False)

3. Python How to write to a json file

3.1 inbuilt module json

import json

data_json = {"name": "Jaxon", "age": 18}

with open("user_data.json", "w") as f:
    json.dump(data_json, f)
Write a file use Python

3.2 use Pandas module

import pandas as pd

data_json = {"name": "Jaxon", "age": 18}

df = pd.DataFrame([data_json])
df.to_json("user_data.json", orient="records")
Write a file use Python

4. Python How to write to a excel file

4.1 Using model xlwt

import xlwt

def write_excel():
    """
    Write to Excel
    """
    file_name = "user_data.xls"
    excel_file = xlwt.Workbook()
    sheet_main = excel_file.add_sheet('main')
    
    # excel header index
    row = 0
    col = 0
    col1 = 1
    value_name = 'Jaxon'
    value_age = 18
    sheet_main.write(row, col, "name")
    sheet_main.write(row, col1, "age")
    sheet_main.write(1, 0, value_name)
    sheet_main.write(1, 1, value_age)
    excel_file.save(file_name)
Write a file use Python
Write a file use Python

4.2 Using pandas module

import pandas as pd

data_json = {"name": "Jaxon", "age": 18}

df = pd.DataFrame([data_json])
df.to_excel("user_data.xlsx", sheet_name="main", encoding="utf-8")
Write a file use Python

codingadmin

Leave a Reply

avatar
  Subscribe  
Notify of