简体   繁体   中英

How to write a counter to an output file in Python?

This is the code I have so far. Is there no way to write it aside from convert it to a string?

outfile = input("What would you like the text file index's name to be?")

if os.path.isfile(outfile):
    print("Name already used, please choose another")
else:
    fp = open(outfile, 'w')
    fp.write(count)
    fp.write(wordCount)
    fp.close

The error I'm getting says that it must be a string to write to an output file. Is there any way around this?

Try this:

with open(outfile, "w") as fp:
    fp.write(str(count))
    fp.write(str(wordcount))

You can only pass strings as arguments to file.write , take a look at the docs .
Here's how you could implement it:

with open(outfile, "w") as fp:
    fp.write(str(count))
    fp.write(str(wordcount))

Note str() around count . This function converts an object to a string, see this page for more info.

HTH.

try fp.write("count")

write function takes only string and string are in the quotes and 'count' is not the integer also that is why you are getting the error while running the code.

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