Exercise 49

  1. Write a Python program that allows you to create a file on desktop called myFile.txt and write on it the content s = 'Python is oriented programming language'. You must at first retrieve the username via the os.getlogin() method.
  2.  write a Python program to read the existing file on the desktop myFile.txt. 

Solution


#------------
# Question 1
#------------
# Importing required module
import os

# Retrieving the user name
user = os.getlogin()

# creating the file myFile.txt on desktop
file = open("C:/Users/" + user + "/Desktop/myFile.txt", 'w')

# writing on myfile.txt
s = 'Python is oriented programming language'
file.write(s)
file.close()

#------------
# Question 2
#------------
file = open("C:/Users/" + user + "/Desktop/myFile.txt", 'r')
#read myFile.txt and print its content
print(file.read())
file.close()
# Note: a file called myFile.txt is created on your desktop, you can see it

Younes Derfoufi
my-courses.net
2 thoughts on “Solution Exercise 49: create and read file on user desktop”

Leave a Reply