简体   繁体   中英

Python: TypeError: unsupported operand type(s) for +: '_io.TextIOWrapper' and 'str'

What I want to do:

I want to print a filename. I could see the output file is available. But I'm unable to print the filename alone.

Python code:

today=datetime.datetime.today().strftime("%Y%m%d-%H%M%S")
string_file="string_"+today+".csv"
outputFile = open(string_file_rdkb, "w")
#....some code here...
my_df=pd.DataFrame(datalist2)
my_df.to_csv(outputFile, index=False, header=False)
print(outputFile + " is generated") #Here is the issue

Output shows:

print(outputFile + " is generated")
TypeError: unsupported operand type(s) for +: '_io.TextIOWrapper' and 'str'

What I tried to solve:

print(str(outputFile) + " is generated")

Output Shows:

<_io.TextIOWrapper name='string_20181213-160004.csv' mode='w' encoding='cp1252'> is generated

Expected Output:

string_20181213-160004.csv is generated

Try using the variable string_file that you've defined, as this is just the name of the file already in a string format;

today=datetime.datetime.today().strftime("%Y%m%d-%H%M%S")
string_file="string_"+today+".csv"
outputFile = open(string_file_rdkb, "w")
#....some code here...
my_df=pd.DataFrame(datalist2)
my_df.to_csv(outputFile, index=False, header=False)
print(string_file+ " is generated") #Here is the issue

Output:

>>> string_20181213-160004.csv is generated

What you were printing before is the file object that is a result of calling open() on the file name, hence it's returning the object itself as opposed to just the name.

只需使用: print(outputFile.name + " is generated")

outputFile is a pointer to the file, not the actual name:

Use this instead:

import os
name = os.path.basename(outputFile.name)
print(name + " is generated")

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