我有一个str类型的输出。我想将其写入文件,但显示此错误。
我尝试了write
和to_excel
命令,但给出了相同的错误。
错误:
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'
我的代码:
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
答案 0 :(得分:1)
如果第一个答案没有保存您所有的输出,那是因为它每次都会覆盖您的文件。
做:
list = []
for name in files:
list.append(name.strip())
with open("file.csv", "w") as file:
for element in list:
file.write(element + "\n")
这应该可以解决您的问题!
答案 1 :(得分:0)
没有用于字符串的to_csv()
方法。
尝试做:
with open("file.csv","w") as file:
file.write(data + "\n")