PYTHON 35 You must have a function named save data string wh
PYTHON 3.5
You must have a function named save data string which takes as input a string, and saves the
string to a file called data file.txt. Nothing is returned. Make sure this function works even if
the file hasn’t been created yet, and if the file does already exist, make sure this function replaces whatever is on the file with the new string. You may assume the user gives a string as intended, and not an integer or anything.
Solution
The code has been explained along by means of comments. Refer to it to understand. Also make sure that you don\'t change the indentation of the code since python relies on indentation for it to work.
Here is the code for writing a user input to the file:
(It creates a file if it does not exist and overwrites the existing string in the file if it does. Save it as someFileName.py and run it in python 3.5 and it will work.)
#!/usr/bin/python
#Function which helps us to write a string to a file
def writeToFile(myString):
# Open a file if it exists or create a new file if it does not in writing mode
fo = open(\"file.txt\", \"w\")
# Write the string to the file
fo.write(myString);
# Close the file
fo.close()
return
#Take user input and store it in a string
myString = input(\"Please enter a string to write to file: \")
#Pass the string to the function which we defined above
writeToFile(myString);
