简体   繁体   English

使用Python Loop从Excel文件创建多个.txt文件

[英]Creating Multiple .txt files from an Excel file with Python Loop

My work is in the process of switching from SAS to Python and I'm trying to get a head start on it. 我的工作正在从SAS转换为Python的过程中,我正在努力抢先一步。 I'm trying to write separate .txt files, each one representing all of the values of an Excel file column. 我正在尝试编写单独的.txt文件,每个文件代表一个Excel文件列的所有值。

I've been able to upload my Excel sheet and create a .txt file fine, but for practical uses, I need to find a way to create a loop that will go through and make each column into it's own .txt file, and name the file "ColumnName.txt". 我已经能够上载Excel工作表并创建一个.txt文件,但是对于实际用途,我需要找到一种创建循环的方法,该循环将遍历每一列并将其设为自己的.txt文件,并命名文件“ ColumnName.txt”。

Uploading Excel Sheet: 上载Excel工作表:

import pandas as pd 将熊猫作为pd导入

wb = pd.read_excel('placements.xls') wb = pd.read_excel('placements.xls')

Creating single .txt file: (Named each column AZ for easy reference) 创建单个.txt文件:(命名每列AZ以方便参考)

with open("A.txt", "w") as f: 使用open(“ A.txt”,“ w”)为f:

for item in wb['A']:
    f.write("%s\n" % item)

Trying my hand at a for loop (to no avail): 在for循环上尝试我的手(无济于事):

import glob 导入球

for file in glob.glob("*.txt"): 对于glob.glob(“ *。txt”)中的文件:

    f = open(( file.rsplit( ".", 1 )[ 0 ] ) + ".txt", "w") 
    f.write("%s\n" % item)
    f.close()

The first portion worked like a charm and gave me a .txt file with all of the relevant data. 第一部分的工作原理很吸引人,为我提供了一个包含所有相关数据的.txt文件。

When I used the glob command to attempt making some iterations, it doesn't error out, but only gives me one output file (A.txt) and the only data point in A.txt is the letter A. I'm sure my inputs are way off... after scrounging around forever it's what I found that made sense and ran, but I don't think I'm understanding the inputs going in to the command, or if what I'm running is just totally inaccurate. 当我使用glob命令尝试进行一些迭代时,它不会出错,而只给我一个输出文件(A.txt),并且A.txt中唯一的数据点是字母A。我确定输入很遥远...一直摸索着,这才是我认为有意义并可以运行的东西,但是我不认为我在理解输入到命令中的输入,或者如果我正在运行的内容完全不准确。

Any help anyone would give would be much appreciated! 任何人的任何帮助将不胜感激! I'm sure it's a simple loop, just hard to wrap your head around when you're so new to python programming. 我确信这是一个简单的循环,当您刚接触python编程时,很难把头缠住。

Thanks again! 再次感谢!

I suggest use pandas for write files by to_csv , only change extension to .txt : 我建议使用熊猫通过to_csv写入文件,仅将扩展名更改为.txt

# Uploading Excel Sheet:
import pandas as pd

df = pd.read_excel('placements.xls')

# Creating single .txt file: (Named each column A-Z for easy reference)

for col in df.columns:
    print (col)
    #python 3.6+ 
    df[col].to_csv(f"{col}.txt", index=False, header=None)
    #python bellow
    #df[col].to_csv("{}.txt".format(col), index=False, header=None)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM