想要将列表转换为 Python 中的逗号分隔文件?
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
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]
我有一个原始文件:
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
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]