【问题标题】:Want to convert the list to a comma separated file in Python?想要在 Python 中将列表转换为逗号分隔的文件?
【发布时间】:2017-05-06 05:43:23
【问题描述】:

我有一个原始文件:

RollNo    Address1    City    State    ZipCode    Age    Branch    Subject    Marks1    Marks2
10000        6505 N MGM W   ROAD                                                                                  MMUMBAI CITY                   IN      46360                          77          0              0             -1          1 
10002        1721 HAZAREER DR. DR. UNIT 8                                                                         BELAGHIA                       FL      33756                          86          0              0             -1          2

如何在 python 中将其转换为逗号分隔的文件:

RollNo,Address1,City,State,ZipCode,Age,Branch,Subject,Marks1,Marks2
10000,6505 N MGM W   ROAD,MMUMBAI CITY,IN,46360,77,0,0,-1,1 
10002,1721 HAZAREER DR. DR. UNIT 8,BELAGHIA,FL,33756,86,0,0,-1,2

我尝试将其转换为列表,因此稍后我可以将其转换为逗号分隔的字符串,使用 \t 作为分隔符,但似乎它不会给我想要的输出。

我的代码是:

files_list=[[i for i in line.strip().split('    ')] for line in open('C:/Users/Vinny/Desktop/Python/file2cnvrt.txt').readlines()]

我得到的输出:

[['RollNo', 'Address1', 'City', 'State', 'ZipCode', 'Age', 'Branch', 'Subject', 'Marks1', 'Marks2'], 
['10000        6505 N MGM W   ROAD                                                                                  MMUMBAI CITY                  IN      46360                          77          0              0             -1          1'], 
['10002        1721 HAZAREER DR. DR. UNIT 8                                                                         BELAGHIA                      FL      33756                          86          0              0             -1          2']]

谁能推荐?

【问题讨论】:

  • 所有的行都对齐吗?如果它们不是制表符分隔的,那么你可能会幸运地直接切片
  • 看来你这里有几个答案。如果其中一个解决了你的问题,别忘了accept one

标签: python python-3.x file-handling


【解决方案1】:

试试这个:

def read_file(filename):
    indices = [13, 113, 145, 153, 184, 196, 211, 225, 237, 0]
    columns = []
    data = []
    with open(filename) as f:
        lines = f.readlines()
    columns = lines[0].strip().split('    ')
    for line in lines[1:]:
        row = []
        line = line.strip()
        for i in range(len(indices) - 1):
            row.append(line[indices[i-1]:indices[i]].rstrip())
        data.append(row)
    return [columns] + data

指数是根据您提供给我们的数据收集的。我假设一切都完美对齐。

【讨论】:

  • 我测试了这段代码。工作正常。唯一的问题是它在标题中给了我 \t 。例如,RollNo\tAddress1\tCity\tState\tZipCode\tAge\tBranch\tSubject\tMarks1\tMarks2
  • @VinnyKaur 然后在上面写着columns = lines[0].strip().split(' ') 的地方把它改成columns = lines[0].strip().split('\t')
【解决方案2】:

这可能不是最优化的方式,尽管它会生成一个逗号分隔的值文件。其中 FILE_IN 和 FILE_OUT 分别是输入和输出文件的文件名。

# Read file lines to list as values
file_in = open(FILE_IN, 'r')
lines_of_values = []
for line in file_in:
    # Split line, remove whitespace and remove empty fields
    line_values = list(filter(None, line.strip().split('    ')))
    values = [value.strip() for value in line_values]
    lines_of_values.append(values)
file_in.close()

# Open file to save comma separated values
file_out = open(FILE_OUT, 'w')
for values in lines_of_values:
    print("{:s}".format(",".join(values)), file=file_out)
file_out.close()

【讨论】:

    【解决方案3】:

    几件事。首先,不要在列表理解中直接使用open()

    如果您想使用open(),请始终使用上下文管理器,它可以保证文件在您完成后将被关闭:

    with open('filename..txt') as f: 
        lines = f.readlines()
    

    第二:你会发现你的生活变得轻松多了,根本不用open(),开始使用神奇的pathlib module

    import Path from pathlib
    f_path = Path('C:/Users/Vinny/Desktop/Python/file2cnvrt.txt')
    # get text as one big string:
    file_str = f_path.read_text()
    # get text as a tuple of lines (splits along new line characters):
    lines_tuple = f_path.read_text().split('\n')
    # get text as a list of lines (use a list if you intend to edit the lines):
    lines = list(f_path.read_text().split('\n'))
    

    第三:无需将整个路径复制粘贴到桌面,您可以使用 Windows USERPROFILE 环境变量自动找到其位置:

    from pathlib import Path
    import os
    # os.getenv just gives you a dictionary with all the Windows environment variables 
    # (such as USERPROFILE and APPDATA)
    user_folder_str = os.getenv['%USERPROFILE%']
    desktop_path = Path(user_folder_str)/'Desktop'
    file_path = Path(user_folder_str)/'Desktop'/'my_file.txt'
    lines = list(file_path.read_text().split('\n'))
    

    第四:您粘贴的示例原始文件中似乎没有任何制表符('\t')。它有 4 个空格 (' ')。如果确实如此,这应该可行:

    [[i for i in line.strip().split('    ') if i] for line in lines]
    

    注意if i 部分。这确保任何 连续 组 4 个空格不会在您的列表中放置空字符串 ('')。

    但是,您粘贴的代码(相当于上述代码)会产生错误的结果。我认为这可能是因为您的第二行和第三行实际上 do 中有制表符 ('\t') 而不是 4 个空格。所以你需要 split() 使用 4 个空格和一个制表符。

    最简单的方法是将制表符替换为 4 个空格。再次使用相同的if i 以避免空字符串。

    [[i for i in line.strip().replace('\t', '    ').split('    ') if i] for line in lines]
    

    【讨论】:

      猜你喜欢
      • 2013-11-14
      • 2019-01-06
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      相关资源
      最近更新 更多