[英]Want to convert the list to a comma separated file in 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
如何在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']]
谁有人建议?
尝试这个:
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
指数是从你给我们的数据中收集的。 我认为一切都完全一致。
这可能不是最优化的方式,但它会生成值的逗号分隔文件。 其中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()
好几件事。 首先,不要在列表推导中直接使用open()
。
如果要使用open()
,请始终使用上下文管理器,以确保在完成文件后将关闭该文件:
with open('filename..txt') as f:
lines = f.readlines()
第二:你会发现你的生活更容易打扰open()
并开始使用惊人的pathlib
模块 。
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
part。 这可以确保任何连续的4个空格集都不会在列表中放置空字符串( ''
)。
但是,粘贴的代码(相当于上述代码)会产生错误的结果。 我想这可能是因为你的第二行和第三行实际上确实有tab字符( '\\t'
)而不是4个空格。 所以你需要使用4个空格和制表符来split()
。
最简单的方法是用4个空格替换标签。 if i
再次使用相同,以避免空字符串。
[[i for i in line.strip().replace('\t', ' ').split(' ') if i] for line in lines]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.