读取 txt 文件时交换位置
Swapping positions when reading a txt file
我正在读取 csv 或 txt 文件。
csv 或 txt 文件具有这种格式(可以有几行相同的格式):
character , Int, character
我想将其更改为这种格式:
character , character , Int
然后将新文件保存为 txt 或 csv。
我有读取 csv 或 txt 文件的代码。
a_list=open(file)
for line in a_list:
#line[1], line[2] = line[2], line[1] # Tried this line but didnt work
print(line)
我得到的结果是:
A,10,B
C,13,D
我想改成:
A,B,10
C,D,13
最好的方法是什么?
解决方案
使用@DarrylG 回答我将代码更改为:
with open('edges.txt') as f:
mylist = [line.rstrip('\n') for line in f]
for line in mylist:
line = line.split(',')
line[1], line[2] = line[2], line[1]
line = ','.join(line)
print(line)
字符串是不可变的。您需要用逗号分隔行以创建一个可以更改其元素的列表。
修改后的代码
with open('test.txt', 'r') as a_list: # It's recommended to use a context manager
# rather than naked open
for line in a_list:
line = line.rstrip().split(',') # Remove trailing '/n' and split on ','
# creating a list
line[1], line[2] = line[2], line[1] # Interchange list elements based upon index
line = ','.join(line) # re-constructs the string
print(line) # show result
输出
A,B,10
C,D,13
我正在读取 csv 或 txt 文件。
csv 或 txt 文件具有这种格式(可以有几行相同的格式):
character , Int, character
我想将其更改为这种格式:
character , character , Int
然后将新文件保存为 txt 或 csv。
我有读取 csv 或 txt 文件的代码。
a_list=open(file)
for line in a_list:
#line[1], line[2] = line[2], line[1] # Tried this line but didnt work
print(line)
我得到的结果是:
A,10,B
C,13,D
我想改成:
A,B,10
C,D,13
最好的方法是什么?
解决方案
使用@DarrylG 回答我将代码更改为:
with open('edges.txt') as f:
mylist = [line.rstrip('\n') for line in f]
for line in mylist:
line = line.split(',')
line[1], line[2] = line[2], line[1]
line = ','.join(line)
print(line)
字符串是不可变的。您需要用逗号分隔行以创建一个可以更改其元素的列表。
修改后的代码
with open('test.txt', 'r') as a_list: # It's recommended to use a context manager
# rather than naked open
for line in a_list:
line = line.rstrip().split(',') # Remove trailing '/n' and split on ','
# creating a list
line[1], line[2] = line[2], line[1] # Interchange list elements based upon index
line = ','.join(line) # re-constructs the string
print(line) # show result
输出
A,B,10
C,D,13