簡體   English   中英

Python 使用 def() 打開和讀取文件並將其以新格式寫入新文件

[英]Python use def() to open and read file and write it in new format into new file

我嘗試打開並更改文件。 該代碼僅適用於前三行,然后是其堆棧。

我的文件是:

Eskil Johnsson
7901105838
Löberöd 29, 521 29  KÄTTLISTORP
Anna Göransson
7102022980
Klubbvägen 18, 770 65  BY KYRKBY    

我的代碼:

def main():
    file_content = read_from_file()
    write_to_file(file_content)

def read_from_file():
    with open('C:\\Users\\saran\\OneDrive\\Dokument\\names2.txt', 'r+', encoding = 'utf_8') as f:
        file_content = []
        line = f.readline()
        line = line.split()
        while(len(line) > 0):
            print(line[1] + ' ' + line[0])
            line = f.readline()
            tal = int(line[8])
            if (tal % 2) == 0:
                print('[K]')
            else:
                print('[M]')
            line = f.readline()
            print(line)
        return file_content

main()

您沒有閱讀 while 語句中的行。

嘗試這個:

    while(len(line) > 0):
        print(line[1] + ' ' + line[0])
        line = f.readline()
        tal = int(line[8])
        if (tal % 2) == 0:
            print('[K]')
        else:
            print('[M]')
        line = f.readline()
        print(line)
        line = f.readline()
        line = line.split()

暫無
暫無

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

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