I wrote this code to remove all new lines from a string' yet it prints the value with \n I still get this output: 4762-9539\n' how can I remove all the \n from this string?
#!/usr/bin/python3
import os
import subprocess
bash_command_lsbk = 'lsblk /dev/sdb1 > /home/user/Downloads/usb_id'
file_path = '/home/user/Downloads/ddd'
usb_id = '/home/user/Downloads/usb_id'
read_permission = 'r'
write_permission = 'w'
def print_usb_id():
url = os.system(bash_command_lsbk)
line = str(subprocess.check_output(['tail', '-1', usb_id])).split('/')[-1]
x = open(file_path, write_permission)
x.write(line)
def read():
with open(file_path, 'r') as new_file_format:
for new_line in new_file_format:
new_line = new_line.rstrip('\n')
print(new_line)
if __name__ == '__main__':
print_usb_id()
read()
You didn't convert the byte string to a string correctly. That's why you got additional characters into your string. Instead of
str(subprocess.check_output(['tail', '-1', usb_id]))
you should write
subprocess.check_output(['tail', '-1', usb_id]).decode('utf-8')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.