Python write String to a file

By: On:

In this Python tutorial, we will discuss how to write a string to a file in Python with examples. Here we will check

  • Python write string to a file
  • Python write string to a file with newline
  • Python write string to a file overwrite
  • Python write string to a file without newline
  • Python write string to a file append
  • Python write string to csv file
  • Python write a single row to a csv file
  • Python write to file for loop
  • Python write binary string to a file
  • Python write to file concatenate string
  • Python write string to file as utf-8
  • Python write string to csv files without quotes

Python write a string to a file

Now let us see how to write a string to a file in Python.


In this example, I have taken textfile = open(“filename.txt, mode) to open the file, and “w” mode to write a file, there are other modes in the files such as:

  • r – read mode.
  • a – append mode.
  • w – writing mode.
  • r+ – both read and write mode.
  • Here, a =textfile.write(‘string’) is used to write a string in the new file created. I have taken the filename as “example.txt” textfile.close() is used to close the file.

Example:

textfile = open("example.txt", "w")
a = textfile.write('pythonguides')
textfile.close()

Below images shows the output in which we can see a string in a file

Python write a string to a file
Python write a string to a file

Python write string to a file with newline

Now, we will see in Python, how to write string to a file with newline character“\n”.


In this example, I used open(“filename.txt, mode) to open the file. And then call file.write(‘string\n’) to write the string in the newly created file.

And then use “\n “it gives a linebreak in the output and the output maker will go to the next line, and then I have used the file.close() to close the file.

Example;

file = open("example.txt", "w")
file.write('Hello all! \nwelcome to pythonguides')
file.close

Below images shows the output:

Python write string to a file with newline
Python write string to a file with newline

Here we can see the two strings are in different lines.

Python write a string to a file overwrite

Here, we can see how to overwrite a string in the file in Python.

In this example, I have used file = open(“file.txt”, mode) to open the file.

Then I took a string variable as fruits = (“mango is yellow”).

Then used file.writelines(fruits) to write the sequence of string to a file and file.close() to close the file.

Example:

file = open("example.txt", "w") 
fruits = ("mango is yellow") 
file.writelines(fruits) 
file.close() 

 

Below example shows the output:

Python write string to a file overwrite
Python write string to a file overwrite

In this example, I used “w” mode to write a new string in the file which is already opened

Example:

file = open("example.txt", "w") 
file.write("vegetables \n") 
file.close() 

Below example shows the output:

Python write string to a file overwrite
Python write string to a file overwrite

In this example,I used file.read() method to overwrite the string.and file.close() to close the file.

Example:

file = open("example.txt", "r") 
print("Output of Readlines after writing") 
print(file.read()) 
print() 
file.close()

Below example shows the output:

overwrite3
Python write string to a file overwrite

This is the final code to overwrite a string.

file = open("example.txt", "w") 
fruits = ("mango is yellow") 
file.writelines(fruits) 
file.close() 

file = open("example.txt", "w") 
file.write("vegetables \n") 
file.close()

file = open("example.txt", "r") 
print("Output of Readlines after writing") 
print(file.read()) 
print() 
file.close()

Python write string to a file append

Now, let us see how to append a string to a file in Python.

append means to add something at the end of the written document (existing document).

In this example, “and green” is appended which is added to an existing string and gives the final string.

To append mode “a” is used (file = open(“example.txt”, “a”)), file.read() is used to read the appended string.

Example:

file = open("example.txt", "w") 
fruit = ("mangoes are yellow")
file.writelines(fruit) 
file.close() 
   
file = open("example.txt", "a")  
file.write(" and green \n") 
file.close() 
   
file = open("example.txt", "r") 
print("Output of Readlines after appending") 
print(file.read()) 
print() 
file.close()

Below image shows the output:

Python write string to a file append
Python write string to a file append

Python write string to a file without newline

Now we can see how to write string to file without newline in Python.

In this example,I used “\r” instead of “\n”

file = open("hello.txt", "w")
file.write('Hello all'"\r")
file.write('welcome to pythonguides')
file.close

Below image shows the output:

Python write string to a file without  newline
Python write string to a file without newline

Python write string to csv file

Let us see how to write a string in a csv file in Python.

CSV file is comma separated value file, It is a simple file format in which tabular form of data is stored. such as excel sheet, database. The csv file should have .csv an extension.

Example:

In this example, I have taken a list of strings as fruits:

fruits = ['apple','cherry','orange','pineapple','strawberry']

Then I have used open(“filename.csv, mode) to open the file. dialect=’excel’ is used to define excel format it contains a group of parameters. writerow(item) is a method to write a row of data in the specified file.

Example:

import csv

fruits = ('apple','cherry','orange','pineapple','strawberry')

fruitfile = open("fruits.csv",'w')
wr = csv.writer(fruitfile, dialect='excel')
for item in fruits:
wr.writerow(item)

Below image shows the output:

Python write string to csv file
Python write string to csv file

In this output we can see all the strings are seperated by comma.

Python write a single row to a csv file

Here we can see how to get a singlerow in a csv file. In this example, I have imported csv module file = open(“filename.csv”,mode) csv.writer() method is used to create write object writerow(item) fuction is used to write single row in csv file.

Example:

import csv
file = open("dict.csv", "w")
writer = csv.writer(file)
writer.writerow(["pen", "pencil"])
file.close()

Below image shows the output:

Python write a single row to a csv file
Python write a single row to a csv file

Python write to file for loop

Here we can see how to write a file for loop in Python.

A for loop is used to iterating over a sequence, we can also use range function(). The rangefunction returns a sequence of numbers starting by 0 by default increments by 1.

file = open("example.txt", "w")
file.write("python guides")
a = "python guides"
for x in a:
print(a)
file.close()

Below image shows the output:

Python write to file for loop
Python write to file for loop

Python write binary string to a file

Now let us see how to convert binary string to a file.

In this example, I used file = open(filename.txt, mode) to open a file and used ‘w+b’mode which is used to write a file in binary format.

Assigned a binarystring =”01100011 01100011 01100001″and binaryvalues = binarystring.split() to split the string on whitespace.

an_integer = int(binaryvalue, 2) this is used to convert base2 decimal integer.

ascii_character = chr(an_integer) and it is used to convert to ASCII character ascii_string += ascii_character this is used to append a character to string print(ascii_string)used to print a string, file.close() to close the file.

Example:

file = open('binary.txt', 'w+b')

binarystring ="01100011 01100011 01100001"

binaryvalues = binarystring.split()

ascii_string = ""

for binaryvalue in binaryvalues:
    an_integer = int(binaryvalue, 2)

    ascii_char = chr(an_integer)

    ascii_string += ascii_char
print(ascii_string)
file.close()

Below image shows the output in which you can see the converted string.

Python write binary string to a file
Python write binary string to a file

Python write to file concatenate string

Here we can see how to write a file to concatenate a string in python. concatenation means the joining of two character strings end-to-end, for example, the concatenation of “foot” and “ball” is “football”

Example:

file = open('o.txt' ,'w')
str1 = "foot"
str2 = "ball"
print("".join([str1, str2])) 
str3 = " ".join([str1, str2]) 
file.write(str3)
file.close()

In this example,I have take file = open(‘filename.txt’ ‘mode’) to open the file and taken two strings as str1=”foot” and str2=”ball”, print(“”.join([str1, str2])) is used to join two strings .str3 = ” “.join([str1, str2]) to join the string with seperator space,to write the concatenated string in the file file.write(str3) is used,file.close() to close the file.

Below image shows the output:

Python write to file concatenate string
Python write to file concatenate string

Python write string to file as utf-8

utf-8- Unicode transformation format, it is an encoding system for Unicode and normally used to encode email and webpages.

Here we can see how to write a string to file as utf-8 format in python.

Example:

file = open('q.txt', 'w+b')
utf8 = "python, guides!".encode()
print(utf8)
b =utf8.decode()
print(utf8.decode())
str(b'abc','utf-8')
file.write(utf8)
arr = bytes(b, 'utf-8')
file.write(arr)
file.close()

In this example,I have used file = open(‘q.txt’,’mode)to open the file,‘w+b’mode is used to write only in binary format.

utf8 = “python, guides!”.encode() ,call string.encode() to encode the string to utf-8 bytes and next call bytes.decode() to decode utf-8 encoded bytes to unicode a string.

file.write(utf8) to write encoded value to the file .To convert string into byte str(b’abc’,’utf-8′) is used and to convert byte to string arr = bytes(b, ‘utf-8’) and file.write(arr) to write the decoded value in the file and lastly file.close() to close the file.

Below image shows the both encoded and decoded value .

Python write string to file as utf-8
Python write string to file as utf-8

Below image shows the output:

Python write string to file as utf-8
Python write string to file as utf-8

Python write string to csv files without quotes

Now we can see how to write a csv file without quotes in python.

In this example, I have imported the CSV module and to open a file I used f= open(“filename.csv”, “mode”) and csv. writer () is used to insert data into CSV file as we require to write a string to CSV file without quotes so I used QUOTE_NONE to get a file without quotes.

To write all the elements in rows writer.writerow() is used.

Example:

import csv
f = open("fruit.csv", "w")
writer = csv.writer(f, quoting=csv.QUOTE_NONE)
writer.writerows([["mango",1],["orange",2]])
f.close()

Below image shows the output:

Python write string to csv files without quotes
Python write string to csv files without quotes

You may like the following Python tutorials:

In this tutorial, we learned about how to write a string to a file and covered the below topics:

  • Python write string to a file
  • Python write string to a file with newline
  • Python write string to a file overwrite
  • Python write string to a file without newline
  • Python write string to a file append
  • Python write string to csv file
  • Python write a single row to a csv file
  • Python write to file for loop
  • Python write to file concatenate string
  • Python write string to file as utf-8
  • Python write string to csv files without quotes

Leave a Comment