我有一个看起来像这样的文件:
1 1:10 2:10 3:40
2 1:30 3:40 4:20
1 1:20 4:40 3:30
我想更改第一个字符,分别为1或2或1到-1,1和-1。
我编写了以下python代码
with open('filename') as f:
lines = f.readlines()
for line in lines:
if line[0] == '1':
print(line)
line = line.split();
line[0] = "-1"
line = "".join(line)
else:
line = line.split("");
line[0] = "1"
通过拆分删除空格字符,我不认为可以将其写入输出文件。我的输出应该最终看起来像这样
-1 1:10 2:10 3:40
1 1:30 3:40 4:20
-1 1:20 4:40 3:30
编写修改文件的代码是
with open('changed_file', 'w') as fout:
for line in lines:
fout.write(line)
答案 0 :(得分:3)
line = "1 1:10 2:10 3:40"
map = {'1': '-1', '2': '1'}
print map[line[0]] + line[1:-1]
#-1 1:10 2:10 3:4
您还可以为map
词典设置默认值。
最佳, 阿尔瓦罗。
答案 1 :(得分:2)
问题是,在更改了你的行之后,你应该用空格连接它们,当它应该以间隔连接时。
for idx, line in enumerate(lines):
split_line = line.split()
if split_line[0] == '1':
split_line[0] = "-1"
else:
split_line[0] = "1"
lines[idx] = " ".join(split_line)
答案 2 :(得分:1)
这会读入所有行,并按照您的说法更改以1
或2
开头的行,然后继续使用已编辑的行重写文件。
with open('<file_name>', 'r+') as f:
lines = f.readlines()
f.seek(0) # moves cursor back to the beginning of the file
for line in lines:
if line.startswith('1'): line = '-1' + line[1::]
elif line.startswith('2'): line = '1' + line[1::]
f.write(line)
新文件内容:
-1 1:10 2:10 3:40
1 1:30 3:40 4:20
-1 1:20 4:40 3:30
答案 3 :(得分:0)
此代码应该有效:
with open('filename') as f:
lines = f.readlines()
with open('output', 'w') as output:
for line in lines:
if line[0] == '1':
line = "-1" + line[1:]
else:
line = "1" + line[1:]
print(line, file=output, end="")