簡體   English   中英

如何在文件中換行?

[英]How to write in new line in a file?

我需要創建一個程序,根據姓氏的第一個字母將人們的信息(例如,姓氏)保存在文本文件中,因此,如果姓氏以K開頭,它將進入MyFile1

我需要像我已經做過的那樣循環,因為這是一個未知數的人,但是我希望每個人都可以在文本文件中的不同行中書寫,這是一種方法。

底部的代碼將每個單獨的信息放入換行符,但我不想讓每個人都出現在換行符中。

MyFile1 = open("AL.txt", "wt")
MyFile2 = open("MZ.txt", "wt")
myListAL = ([])
myListMZ = ([])

while 1: 
    SurName = input("Enter your surname name.")
    if SurName[0] in ("A","B","C","D","E","F","G","H","I","J","K","L"):
        Title = input("Enter your title.")
        myListAL.append(Title);
        FirstName = input("Enter your first name.")
        myListAL.append(FirstName);
        myListAL.append(SurName);
        Birthday = input("Enter birthdate in mm/dd/yyyy format:")
        myListAL.append(Birthday);
        Email = input("Enter your email.")
        myListAL.append(Email);
        PhoneNumber = input("Enter your phone number.")
        myListAL.append(PhoneNumber);
        for item in myListAL:
            MyFile1.write(item+"\n")

    elif SurName[0] in ("M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"):
        Title = input("Enter your title.")
        myListMZ.insert(Title);
        FirstName = input("Enter your first name.")
        myListMZ.append(FirstName);
        myListMZ.append(SurName);
        Birthday = input("Enter birthdate in mm/dd/yyyy format:")
        myListMZ.append(Birthday);
        Email = input("Enter your email.")
        myListMZ.append(Email);
        PhoneNumber = input("Enter your phone number.")
        myListMZ.append(PhoneNumber);
        line.write("\n")
        for item in myListMZ:
            MyFile2.write(line)

    elif SurName == "1":
        break


MyFile1.close()
MyFile2.close()

您正在尋找join

當您具有項目列表時,可以將其與單個字符串連接在一起。

l = ['a', 'b', 'c']
print(''.join(l))

產生

abc

您不僅可以使用空字符串,還可以使用另一個字符串作為分隔符

l = ['a', 'b', 'c']
print(', '.join(l))

現在產生

a, b, c

在您的示例中(例如,第一次write

MyFile1.write(','.join(MyListAL) + '\n')

如果您碰巧在列表中有不是字符串的內容:

MyFile1.write(','.join(str(x) for x in MyListAL) + '\n')

(您也可以使用map ,但是生成器表達式就足夠了)

編輯:添加map

MyFile1.write(','.join(map(str, MyListAL)) + '\n')

在您的情況下,我寧願使用詞典列表,其中所有信息的人都是字典。 然后,您可以將其轉換為JSON字符串,這是表示數據的標准格式。 (否則,您需要定義自己的格式,在項目之間使用定界符。)

所以像這樣:

import json # at the top of your script

# I would create a function to get the information from a person:
def get_person_input():
   person = {}
   person["surname"] = input("Surname: ")
   person["title"] = input("Title: ")
   person["email"] = input("Email: ")
   # TODO: do whatever you still want

   return person


# Later in the script when you want to write it to a file:
new_line = json.dumps( person )

myfile.write( new_line + "\n" )

畢竟,解析json也非常容易:

person = json.loads(current_line) # you can handle exception if you want to make sure, that it is a JSON format

您可以在代碼中使用如下代碼來決定應該在哪個數組中編寫:

SurName = input("Enter your surname name.")
if SurName[0] <= 'L':
    ...
else:
    ...

這將使您的腳本更加清晰和健壯。

暫無
暫無

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

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