Exercise 49
- 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.
- 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
my-courses.net
where can we see output
Press the F5 key on the keyboard to see the program output on your IDE !