【问题标题】:Write input file with any number of lines to tab-delimited output将具有任意行数的输入文件写入制表符分隔的输出
【发布时间】:2020-09-22 22:18:43
【问题描述】:

我正在尝试编写一个脚本,该脚本将获取一个包含未知数量的列的输入文件,以逗号分隔,并创建一个新文件(由用户指定的名称),其中列由制表符分隔。

我正在使用的测试输入文件如下所示:

Data 1,35,42,7.34,yellow,male
Data 2,41,46,8.45,red,female

这是我目前的代码:

# Read input file
infile = open("input_file.txt", "r")

line_count = 0

# Read as a collection, removing end line character
for line in infile:
    print(line, end = "")
print("The input file contains", line_count, "lines.")

# Request user input for output file name
filename = input("Enter a name for the output file: ")

# Prompt for file name if entry is blank or only a space    
while filename.isspace() or len(filename) == 0:
    
    filename = input("Whoops, try again. Enter a name for the output file: ")

# Complete filename creation
filename = filename + ".txt"
filename = filename.strip()

# Write output as tab-delim file
for line in infile:
    outfile = open(filename, "w")
    outfile.write(line,"\t")
    outfile.close()

print("Success, the file", filename, "has been written.")
    
# Close input file
infile.close()

写入输出的部分不起作用 - 它不会产生错误,但输出为空白。

【问题讨论】:

标签: python


【解决方案1】:

您可以在添加制表符(\t)字符时用逗号分隔行并编写:

with open('input_file.txt','r') as f_in, open('output_file.txt', 'w') as f_out:
    for line in f_in:
        s = line.strip().split(',')
        for i in s:
            f_out.write(i+'\t')
        f_out.write('\n')

或像@martineau 建议的那样简短:

with open('input.txt','r') as f_in, open('output.txt', 'w') as f_out:
    for line in f_in:
        s = line.strip().split(',')
        f_out.write('\t'.join(s) + '\n')

【讨论】:

  • 您不应该使用像 str 这样的内置名称作为变量名。忽略这个问题,你可以f_out.write('\t'.join(str) + '\n')
  • 为了澄清,因为我还在学习,我需要重新读取输入文件,尽管已经在程序的前面读取过它?这行得通,我只需要将 open(output_file.txt', 'w') 更改为 open(filename, 'w') 以接受用户输入的文件名。
  • @happymappy:这只是读取输入文件一次……同时写入输出文件。
【解决方案2】:

您可以使用pandas:

import pandas as pd
df = pd.read_csv("input_file.txt", sep=',',header=None)
print("The input file contains", df.shape[0], "lines.")
filename = input("Enter a name for the output file: ").strip()

# Prompt for file name if entry is blank or only a space    
while filename.isspace() or len(filename) == 0:
    filename = input("Whoops, try again. Enter a name for the output file: ")
    
#Saving to csv with | separator
df.to_csv(f'{filename}.txt', sep="\t", header=None, index=None)

print("Success, the file", filename, "has been written.")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多