簡體   English   中英

如何使用python更改文件中每個新行的第一個字符

[英]How to change the first charcater of every new line in a file using python

我有一個看起來像這樣的文件:

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)

你考慮過這樣的事情嗎?

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 dict。

最好,阿爾瓦羅。

問題是,在更改行后,您應該在空白處將它們連接起來,而應該以一定的間隔將它們連接起來。

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)

這將讀取所有行,並按照您所說的更改以12開頭的行,然后繼續使用編輯的行重寫文件。

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

此代碼應工作:

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="")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM