删除从.txt文件

时间:2016-01-03 16:45:29

标签: python variables text-files newline python-3.4

问题:

总而言之,我想删除,起飞,摆脱变量中包含的额外空白行,该变量本质上是从.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,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变量中

请帮忙!我到处搜索,没有发现任何特定的问题,提前谢谢!

3 个答案:

答案 0 :(得分:1)

不是直接将其写入文件,而是首先将其保存在变量中并一次写入。你可以这样做,

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)

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您的问题不是\n中神奇地产生的line(新行字符)。

将字符串写入文件是write函数。 write的每次调用都会在输出文件中开始一个新行。

也许你应该连接输出字符串并将all all写入文件。

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)
相关问题