簡體   English   中英

從.txt文件讀取的變量末尾刪除換行符

[英]Removing newline at the end of a variable read from .txt file

問題:

總而言之,我要刪除,刪除,擺脫包含在變量中的多余空白行,該行本質上是從.txt文件讀取的行

更詳細地:

因此,情況是這樣的:我有一個程序,該程序從兩個.txt文件中獲取數據,並將每個文件中的部分數據組合在一起,以創建一個新文件,其中包含兩個文件中的數據

    search_registration = 'QM03 EZM'
    with open('List of Drivers Names and Registrations.txt', 'r') as search_file, open('carFilesTask1.txt', 'r') as search_av_speed_file, open('Addresses Names Registrations Speeds to Fine.txt', 'a') as fine_file:
        for line in search_file:
            if search_registration in line:
                fine_file.write(line)
        for line in search_av_speed_file:
            if search_registration in line:
                current_line = line.split(",")
                speed_of_car = current_line[2]
                print(speed_of_car)
                fine_file.write(speed_of_car)

在第二個for循環中,程序將搜索.txt文件,該文件具有與第一個for循環中搜索的相同速度的平均車牌注冊,並使用文本文件中的逗號分割具有此注冊的行:

QM03 EZM,1.0,1118.5

平均速度為“ 1118.5”,因為它是該行的第三部分。

但是...當從下面顯示的列表中編寫具有所需注冊的行時,似乎添加了我不希望的換行符

此列表的一個示例是:

CO31 RGK,尼爾·戴維森,YP3 2GP

QM03 EZM,蒂莫西·羅傑斯(Timothy Rogers),RI8 4BX

EX97 VXM,佩德羅·凱勒,QX20 6PC

輸出的示例是

IS13 PMR,Janet Bleacher,XG3 8KW

2236.9

QM03 EZM,蒂莫西·羅傑斯(Timothy Rogers),RI8 4BX

1118.5

如您所見,汽車的速度不同,一個以2236.9行駛,另一個以1118.5 ,顯示該程序每次重新運行的第二行上的字符串是從第二個原始文件中提取的(與速度一)

我只想擺脫該空白行,而不是原始文件內,而是從文件中讀取后在line變量內

請幫忙! 我到處搜索,還沒有發現任何特定於此問題的信息,在此先感謝您!

與其直接將其寫入文件,不如先將其保存到變量中並立即寫入。您可以這樣操作,

for line in search_file:
    if search_registration in line:
        str1 = line;
for line in search_av_speed_file:
    if search_registration in line:
         current_line = line.split(",")
         speed_of_car = current_line[2]
         print(speed_of_car)
         str2 = speed_of_car
fstr=" ".join(str1,str2) #further formatting can be done here,like strip() and you can print this to see the desired result
fine_file.write(fstr)

這樣,根據需要格式化字符串會容易得多。

Ockhius的答案當然是正確的,但是要刪除字符串開頭和結尾的多余字符: str.strip([chars])

你的問題不是\\n (換行字符),在神奇產卵line

這是將字符串寫入文件的write功能。 每次調用write都會在輸出文件中開始新的一行。

也許您應該連接輸出字符串並將其全部寫入文件。

search_registration = 'QM03 EZM'
with open('List of Drivers Names and Registrations.txt', 'r') as search_file, open('carFilesTask1.txt', 'r') as search_av_speed_file, open('Addresses Names Registrations Speeds to Fine.txt', 'a') as fine_file:
    for line in search_file:
        if search_registration in line:
            first = line
    for line in search_av_speed_file:
        if search_registration in line:
            current_line = line.split(",")
            speed_of_car = current_line[2]
            print(speed_of_car)
            out_str = first + speed_of_car
            fine_file.write(out_str)

暫無
暫無

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

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