简体   繁体   中英

TypeError: TextIOWrapper.write() take no keyword arguments

Been trying to get data to print to an outfile and keep getting this error. When I print the data to the screen (printrec()), everything works, but writerec() does not. I'm not very familiar with python and I've tried several different versions of output.write().

def printrec():
    x = 1
    while x < len(reccomendlist):
        print("User-ID",x,': ', "Movie-ID",reccomendlist[x][0],', ',"Movie-ID",reccomendlist[x][1],', ',"Movie-ID",reccomendlist[x][2],', ',"Movie-ID",reccomendlist[x][3],', ',"Movie-ID",reccomendlist[x][4], sep = '')
        x += 1

def writerec():
    with open("output.txt", "w") as output:
    #encoding = 'utf-8'

        x = 1
    while x < len(reccomendlist):
        output.write("User-ID",x,': ', "Movie-ID",reccomendlist[x][0],', ',"Movie-ID",reccomendlist[x][1],', ',"Movie-ID",reccomendlist[x][2],', ',"Movie-ID",reccomendlist[x][3],', ',"Movie-ID",reccomendlist[x][4], sep = '')
        x += 1

    output.close()
    #with open("./output.txt", "w") as text_file:
        #x = 1
   # while x < len(reccomendlist):
        #text_file.write("User-ID",x,': ', "Movie-ID",reccomendlist[x][0],', ',"Movie-ID",reccomendlist[x][1],', ',"Movie-ID",reccomendlist[x][2],', ',"Movie-ID",reccomendlist[x][3],', ',"Movie-ID",reccomendlist[x][4], sep = '')
        #x += 1
  1. You don't need the line output.close() , the with-block already closes the file for you.

  2. Your indentation is wrong. It should be

with open("output.txt", "w") as output:
    x = 1
    while x < len(reccomendlist):
        output.write("User-ID",x,': ', "Movie-ID",reccomendlist[x][0],', ',"Movie-ID",reccomendlist[x][1],', ',"Movie-ID",reccomendlist[x][2],', ',"Movie-ID",reccomendlist[x][3],', ',"Movie-ID",reccomendlist[x][4], sep = '')
        x += 1
  1. You can iterate over reccomendlist by doing
for x, element in enumerate(reccomendlist):
    element

instead of

x = 1
while x < len(reccomendlist):
    element = reccomendlist[x]
    x += 1
  1. You can't add the sep parameter to write , this is a print parameter. Use print with the file parameter:
for x, element in enumerate(reccomendlist):
    print("User-ID",x,': ', "Movie-ID",element[0],', ',"Movie-ID",element[1],', ',"Movie-ID",element[2],', ',"Movie-ID",element[3],', ',"Movie-ID",element[4], sep = '', file=output)

Depending of your Python version, it can be even more readable:

for x, row in enumerate(reccomendlist):
    print(f"User-ID{x}", end=': ', file=output)
    print(', '.join(f"Movie-ID{element}" for element in row), file=output)

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