Attributeerror: 'Str' Object Has No Attribute 'To_Csv'

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

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

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.