简体   繁体   中英

python Writing to a file

I am trying to do my first assignment about Writing to a file in python. Can any one help me why I am getting an output of the following type? Thank you! Contents of file log.txt:

Contents of file log.txt should be:

Attencion, attencion. 10, 10, 22, 33, Adios.

My Code is:

fileName=input("Give a file name:: ")
filetext=input("Write something: ")
readfile = open("fileName","w")

readfile.write( filetext )

print("Wrote",filetext," to the file",fileName)

readfile.close()

Assignment: Unsurprisingly, the second exercise in this chapter discusses the task of writing to a file. Create a program which prompts the user for a file name "Give a file name: " and then for an input "Write something: ". After this, the program writes the string given by the user to the file and reports "Wrote [input] to the file [name].". When working correctly, the program prints something like this:

Give a file name: log.txt

Write something: Attencion, attencion. 10, 10, 22, 33, Adios.

Wrote Attencion, attencion. 10, 10, 22, 33, Adios. to the file log.txt.

Example output

Give a file name:: log.txt Write something: Attencion, attencion. 10, 10, 22, 33, Adios. Wrote Attencion, attencion. 10, 10, 22, 33, Adios. to the file log.txt

Your problem is that you use the string "fileName" , instead of the variable name fileName :

readfile = open("fileName","w")

This will create a new file called fileName , not use the name the user supplies (eg log.txt ). Instead, use:

readfile = open(fileName, "w") # remove quote marks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM