总之,我想删除,去掉,去掉一个变量中包含的多余的空行,这个变量本质上是一个从.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
变量之后
请帮帮我!我到处都找过了,没有找到任何与这个问题有关的东西,提前谢谢!你知道吗
Ockhius的答案当然是正确的,但是要删除字符串开头和结尾不需要的字符:str.strip([chars])
与其直接将其写入文件,不如先将其保存在变量中,然后在一次。你呢我可以这样做
通过这种方式,可以更容易地格式化字符串。你知道吗
你的问题不在于
\n
(新行字符)在line
中神奇地产生。你知道吗将字符串写入文件是
write
函数。write
的每次调用都会在输出文件中开始一行新行。你知道吗也许您应该连接输出字符串并将所有内容写入文件。你知道吗
相关问题 更多 >
编程相关推荐