Python, Pandas : write content of DataFrame into text File

前端 未结 7 1939
再見小時候
再見小時候 2020-11-27 11:49

I have pandas DataFrame like this

        X    Y  Z    Value 
0      18   55  1      70   
1      18   55  2      67 
2      18   57  2      75     
3      1         


        
7条回答
  •  一个人的身影
    2020-11-27 12:32

    Way to get Excel data to text file in tab delimited form. Need to use Pandas as well as xlrd.

    import pandas as pd
    import xlrd
    import os
    
    Path="C:\downloads"
    wb = pd.ExcelFile(Path+"\\input.xlsx", engine=None)
    sheet2 = pd.read_excel(wb, sheet_name="Sheet1")
    Excel_Filter=sheet2[sheet2['Name']=='Test']
    Excel_Filter.to_excel("C:\downloads\\output.xlsx", index=None)
    wb2=xlrd.open_workbook(Path+"\\output.xlsx")
    df=wb2.sheet_by_name("Sheet1")
    x=df.nrows
    y=df.ncols
    
    for i in range(0,x):
        for j in range(0,y):
            A=str(df.cell_value(i,j))
            f=open(Path+"\\emails.txt", "a")
            f.write(A+"\t")
            f.close()
        f=open(Path+"\\emails.txt", "a")
        f.write("\n")
        f.close()
    os.remove(Path+"\\output.xlsx")
    print(Excel_Filter)
    

    We need to first generate the xlsx file with filtered data and then convert the information into a text file.

    Depending on requirements, we can use \n \t for loops and type of data we want in the text file.

提交回复
热议问题