TypeError:无法隐式地将'_io.TextIOWrapper'对象转换为str

时间:2016-07-01 13:29:58

标签: python string python-3.x directory

我想将pandas.DataFrame对象保存到.csv文件中(使用DataFrame.to_csv())。为简单起见,情况就是这样;我的项目'Algos'包含文件夹'Plip',文件名为'plop.txt'。

1,2
3,4
5,6   

我的脚本在这里:

import numpy as np
import pandas as pa

# opening the file
dossier = "Plip"
fichier = "plop.txt"
fichier = open(dossier + "/" + fichier)
data = fichier.readlines()

# creating the data frame
Pair = []
Impair = []
for m in data:
    impair = int(m[0:1])
    pair = int(m[2:3])
    Impair.append(impair)
    Pair.append(pair)

M = np.array([Impair, Pair]).transpose()
Table = pa.DataFrame(M, columns = ["Impair", "Pair"])

#creating the .csv file
Table.to_csv(dossier + fichier + ".csv")

表已正确创建,但脚本返回:

runfile('C:/Users/******/Documents/PYTHON/Algos/truc.py', wdir='C:/Users/******/Documents/PYTHON/Algos')
Traceback (most recent call last):

  File "<ipython-input-110-3c7306b8d61d>", line 1, in <module>
    runfile('C:/Users/******/Documents/PYTHON/Algos/truc.py', wdir='C:/Users/******/Documents/PYTHON/Algos')

  File "C:\Users\******\Documents\Gratuiciels\WINPYTHON.3355\python-3.3.5\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 601, in runfile
    execfile(filename, namespace)

  File "C:\Users\******\Documents\Gratuiciels\WINPYTHON.3355\python-3.3.5\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 80, in execfile
    exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)

  File "C:/Users/******/Documents/PYTHON/Algos/truc.py", line 30, in <module>
    Table.to_csv(dossier + fichier + ".csv")

TypeError: Can't convert '_io.TextIOWrapper' object to str implicitly

我对Python很陌生,所以你能在答案上尽可能准确吗?

提前谢谢

1 个答案:

答案 0 :(得分:0)

好像你将fichier重新分配给L7上的文件对象,改为使用新变量!