• We just launched and are currently in beta. Join us as we build and grow the community.

Python File Writing

Uplight

Organic Reach Hacker
U Rep
0
0
0
Rep
0
U Vouches
0
0
0
Vouches
0
Posts
152
Likes
131
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 200 XP
In this tutorial you will learn:

  • File Writing Modes
  • File Writing in Python
  • Deleting a File

File Writing Modes

In Python we have the ‘w,’ ‘a’ and ‘+’ for writing to a file. For appending data to an already written file we use ‘a’

Mode

Description

w

For writing or creating a file.

a

For appending to a file.

+

For opening a file for reading or writing.

File Writing in Python

We can write to new and existing files in Python. For writing we need to perform three main tasks one is to open the file, next one is to write the file and the last step is to close the file after writing.

Example

We will use the ‘w’ mode for this example as the file is not created. We will create the file and write the data into it.

  1. f =

    open

    (

    "myFile.txt"

    ,

    "w"

    )
  2. f.write

    (

    "Example of writing to a file"

    )
  3. f.close

    (

    )

Now in the next example we will append the data to our already created “myFile.txt”. For appending data we need to use the “a” mode.

  1. f =

    open

    (

    "myFile.txt"

    ,

    "a"

    )
  2. f.write

    (

    "Example of appending to a file"

    )
  3. f.close

    (

    )

Deleting a File

To delete a file we need to import a module called OS which gives us a remove method to delete files.

  1. import

    os
  2. os

    .remove

    (

    “myFile.txt

    ")

Book traversal links for Python File Writing

  • ‹ Python File Reading
  • Up
  • Python JSON Parsing ›


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

452,496

331,422

331,430

Top