删除从.txt fi读取的变量末尾的换行符

2024-10-02 04:26:17 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是:

总之,我想删除,去掉,去掉一个变量中包含的多余的空行,这个变量本质上是一个从.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循环中搜索相同的numberplate注册平均速度的.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行驶,显示程序每次重新运行的第二行上的字符串是从第二个原始文件中获取的字符串(具有速度的字符串)

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

请帮帮我!我到处都找过了,没有找到任何与这个问题有关的东西,提前谢谢!你知道吗


Tags: 文件ofin程序txtforsearchas
3条回答

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

与其直接将其写入文件,不如先将其保存在变量中,然后在一次。你呢我可以这样做

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)

通过这种方式,可以更容易地格式化字符串。你知道吗

你的问题不在于\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)

相关问题 更多 >

    热门问题