AttributeError: 'str' object has no attribute 'to_csv'

I have an output which type of is str. I want to write it a file but it shows this error.

I tried write and to_excel commands but it give same error.

Error:

AttributeError Traceback (most recent call last) <ipython-input-43-b62c7c6bb434> in <module> 7 with open(name) as f: 8 data = f.read().replace("\n", " ") ----> 9 data.to_csv("C:\\Users\\frknk\\OneDrive\\Masaüstü\\enron6\\maaail.txt") 10 print(data) 11 except IOError as exc: AttributeError: 'str' object has no attribute 'to_csv' 

My code:

import glob import errno path =r'C:\Users\frknk\OneDrive\Masaüstü\enron6\emails\*.txt' files = glob.glob(path) for name in files: try: with open(name) as f: data = f.read().replace("\n", " ") data.to_csv("C:\\Users\\frknk\\OneDrive\\Masaüstü\\enron6\\maaail.txt") print(data) except IOError as exc: if exc.errno != errno.EISDIR: raise 
4

2 Answers

If the first answer don't save all your output it is because it overwrites your file everytime.

do:

list = [] for name in files: list.append(name.strip()) with open("file.csv", "w") as file: for element in list: file.write(element + "\n") 

this should fix your problem!

2

there is no to_csv() method for strings.

Try doing:

with open("file.csv","w") as file: file.write(data + "\n") 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like