Python Forum
Remove all \n from end of list items
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Remove all \n from end of list items
#4
You are doing two task here making a list and wirte to file.
Let say this is sample.txt.
Output:
203.215.181.219:36342 200.149.0.74:8080 46.209.98.227:8080 150.95.131.174:3128
Now just do the witting to file part and it seems okay.
with open('sample.txt', 'r') as fin:
    data = fin.read().splitlines(True)
with open('sample1.txt', 'w') as fout:
    fout.writelines(data[2:])
Other name sample1.txt so it don't overwrite original in this test.
Output:
46.209.98.227:8080 150.95.131.174:3128
Getting a list without \n could be done like this.
with open('sample.txt', 'r') as fin:
    data = [i.strip() for i in fin]
Output:
>>> data ['203.215.181.219:36342', '200.149.0.74:8080', '46.209.98.227:8080', '150.95.131.174:3128']
Writing back from this list could be.
with open('sample.txt', 'r') as fin:
    data = [i.strip() for i in fin]
with open('sample2.txt', 'w') as fout:
    for ip in data[:2]:
        fout.write(f'{ip}\n')
Output:
203.215.181.219:36342 200.149.0.74:8080
Reply


Messages In This Thread
RE: Remove all \n from end of list items - by snippsat - Dec-27-2019, 08:02 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to parse and group hierarchical list items from an unindented string in Python? ann23fr 0 187 Mar-27-2024, 01:16 PM
Last Post: ann23fr
  unable to remove all elements from list based on a condition sg_python 3 442 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,330 May-22-2023, 10:39 PM
Last Post: ICanIBB
  Finding combinations of list of items (30 or so) LynnS 1 877 Jan-25-2023, 02:57 PM
Last Post: deanhystad
  Remove numbers from a list menator01 4 1,332 Nov-13-2022, 01:27 AM
Last Post: menator01
  For Word, Count in List (Counts.Items()) new_coder_231013 6 2,595 Jul-21-2022, 02:51 PM
Last Post: new_coder_231013
  How to get list of exactly 10 items? Mark17 1 2,522 May-26-2022, 01:37 PM
Last Post: Mark17
  how to assign items from a list to a dictionary CompleteNewb 3 1,582 Mar-19-2022, 01:25 AM
Last Post: deanhystad
  Reading list items without brackets and quotes jesse68 6 4,632 Jan-14-2022, 07:07 PM
Last Post: jesse68
  Remove empty keys in a python list python_student 7 3,030 Jan-12-2022, 10:23 PM
Last Post: python_student

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020