删除从 .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 循环中,程序搜索具有与第一个 for 循环中搜索的相同车牌注册的平均速度的 .txt 文件,并拆分行在文本文件中使用逗号注册:

QM03 EZM,1.0,1118.5

平均速度为“1118.5”,因为这是线路的第三个分段。

然而... 当从下面显示的列表中写入所需注册的行时,它似乎添加了一个我不想要的换行符

此列表的示例是:

CO31 RGK, Niall Davidson, YP3 2GP

QM03 EZM, Timothy Rogers, RI8 4BX

EX97 VXM, Pedro Keller, QX20 6PC

输出的一个例子是

IS13 PMR, Janet Bleacher, XG3 8KW

2236.9

QM03 EZM, Timothy Rogers, RI8 4BX

1118.5

大家可以看到,小车的速度是不一样的,一个在2236.9,一个在1118.5,显示每个re-[=]第二行的字符串程序的43=]是从第二个原始文件(有速度的那个)中取出的

我只想去掉这个空行,不是在原始文件中,而是在从文件中读取后 line 变量中

请帮忙!我到处搜索,但没有找到任何特定于此问题的信息,在此先感谢!

Ockhius 的答案当然是正确的,但是要删除字符串开头和结尾不需要的字符:str.strip([chars])

您的问题不是在 line 中神奇生成的 \n(换行符)。

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)

与其直接写入文件,不如先保存在变量中,然后写入once.You可以这样,

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)

通过这种方式,您可以更轻松地根据需要格式化字符串。