How do you delete \n from a line? - string

I am reading lines from a file and putting them into a list. However, when I read the lines, they read in with a newline (\n). I have tried to remove it with str.strip(), str.rstrip(), str.strip("\n"), str.rstrip("\n"), str.strip("\\n"), and str.rstrip("\\n"), but
none of them have done what I want them to.
Here is the code.
lines=[]
with open(v) as x:
for line in x:
if "\n" in line:
lines.append(line)
for line in lines:
line.strip()
if '\n' in line:
print "I'm a stupid computer."
print lines
This yields precisely this output.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
['6\n', '1 2\n', '2 3\n', '3 1\n', '10 11\n', '100 10\n', '11 100\n', '1 100\n', '2 3\n', '3 2\n']
I'm not sure what I'm missing.

line.strip() creates a copy of the line without the leading/trailing whitespace. You are not doing anything with the copy, you need to assign it back to the line. You want:
line = line.strip()
You could also just use:
with open(v) as fin:
lines = [line.strip() for line in fin.readlines()]
You probably don't want want to only add the lines that contain a newline. Maybe what you do want is to omit those lines that don't contain anything else:
with open(v) as fin:
lines = [line.strip() for line in fin.readlines() if line.strip()]

String objects are immutable in Python. line.strip() doesn't change line; it returns a stripped copy. Use line = line.strip() instead (or better yet for your example, just append the stripped version to the list in the first place:
if "\n" in line:
lines.append(line.strip())

You need to assign the output of strip() back to the variable:
line = line.strip()

\n is one character, you can slice it.
line = line[0:len(line)-1]
or per #Henry's comment,
line[:-1]

Related

How to read a text file and insert the data into next line on getting \n character

I have a text file where data is comma delimited with a litral \n character in between, i would like to insert the data into newline just after getting the \n character.
text file sample:
'what,is,your,name\n','my,name,is,david.hough\n','i,am,a,software,prof\n','what,is,your,name\n','my,name,is,eric.knot\n','i,am,a,software,prof\n','what,is,your,name\n','my,name,is,fisher.cold\n','i,am,a,software,prof\n',..
expected:
I need the output in the below form.
'what,is,your,name',
'my,name,is,david.hough',
'i,am,a,software,prof',
Tried:
file1 = open("test.text", "r")
Lines = file1.readlines()
for line in Lines:
print(line)
result:
'what,is,your,name\n','my,name,is,david.hough\n','i,am,a,software,prof\n','what,is,your,name\n','my,name,is,eric.knot\n','i,am,a,software,prof\n','what,is,your,name\n','my,name,is,fisher.cold\n','i,am,a,software,prof\n',..
well my comment does exactly what you asked, break lines at \n. your data is structured quite weirdly, but if you want the expected result that badly you can use regex
import re
file1 = open("test.text","r")
Lines = re.findall(r'\'.*?\',',file1.read().replace("\\n",""))
for line in Lines:
print(line)
Well you don't need push data to the other line manually. The \n does that work when you run the code.
I guess the problem is that you used quotes very frequently, try using a single pair of quotes and use \n after the first sentence and yeah without white space
'what,is,your,name\nmy,name,is,david.hough\ni,am,a,software,prof'

Python isalpha giving wrong results

with open("text.txt") as f:
for line in f:
line.isalpha()
False
File has only one line and contents are:
"abc"
I think this is because there is a space after the "abc" content
As far as I know file lines are usually terminated by newline character \n which is the answer why isalpha() returns false.
As the others pointed out, it must be for some other characters in the file; likely either "\n" for line termination, or some others.
In brief, you want to remove those characters. Try:
line.strip().isalpha()
Full explanation below.
Load data:
with open("text.txt") as f:
for line in f:
line.isalpha()
The output of line is:
>>> line
'abc\n'
And of course the result of isalpha() is false:
>>> print(line.isalpha())
False
However, removing the \n you obtain the correct result:
>>> line.strip()
'abc'
>>> line.strip.isalpha()
True
(To troubleshoot this, you may want to just output the line in the interpreter, without print statements, otherwise you won't see special characters as '\n')

How to modify and print list items in python?

I am a beginner in python, working on a small logic, i have a text file with html links in it, line by line. I have to read each line of the file, and print the individual links with same prefix and suffix,
so that the model looks like this.
<item>LINK1</item>
<item>LINK2</item>
<item>LINK3</item>
and so on.
I have tried this code, but something is wrong in my approach,
def file_read(fname):
with open(fname) as f:
#Content_list is the list that contains the read lines.
content_list = f.readlines()
for i in content_list:
print(str("<item>") + i + str("</item>"))
file_read(r"C:\Users\mandy\Desktop\gd.txt")
In the output, the suffix was not as expected, as i am a beginner, can anyone sort this out for me?
<item>www.google.com
</item>
<item>www.bing.com
</item>
I think when you use .readLine you also put the end of line character into i.
If i understand you correctly and you want to print
item www.google.com item
Then try
https://www.journaldev.com/23625/python-trim-string-rstrip-lstrip-strip
print(str("") + i.strip() + str(""))
When you use the readlines() method, it also includes the newline character from your file ("\n") before parsing the next line.
You could use a method called .strip() which strips off spaces or newline characters from the beginning and end of each line which would correctly format your code.
def file_read(fname):
with open(fname) as f:
#Content_list is the list that contains the read lines.
content_list = f.readlines()
for i in content_list:
print(str("<item>") + i.strip() + str("</item>"))
file_read(r"C:\Users\mandy\Desktop\gd.txt")
I assume you wanted to print in the following way
www.google.com
When you use readlines it gives extra '\n' at end of each line. to avoid that you can strip the string and in printing you can use fstrings.
with open(fname) as f:
lin=f.readlines()
for i in lin:
print(f"<item>{i.strip()}<item>")
Another method:
with open('stacksource') as f:
lin=f.read().splitlines()
for i in lin:
print(f"<item>{i}<item>")
Here splitlines() splits the lines and gives a list

Removing \n from a list of strings

Using this code...
def read_restaurants(file):
file = open('restaurants_small.txt', 'r')
contents_list = file.readlines()
for line in contents_list:
line.strip('\n')
print (contents_list)
file.close()
read_restaurants('restaurants_small.txt')
I get this result...
['Georgie Porgie\n', '87%\n', '$$$\n', 'Canadian,Pub Food\n', '\n', 'Queen St. Cafe\n', '82%\n', '$\n', 'Malaysian,Thai\n', '\n', 'Dumplings R Us\n', '71%\n', '$\n', 'Chinese\n', '\n', 'Mexican Grill\n', '85%\n', '$$\n', 'Mexican\n', '\n', 'Deep Fried Everything\n', '52%\n', '$\n', 'Pub Food\n']
I want to strip out the \n...I've read through a lot of answers on here that I thought might help, but nothing seems to work specifically with this!
I guess the for...in process needs to be stored as a new list, and I need to return that...just not sure how to do it!
A bit more of a pythonic (and, to my mind, easier to read) approach:
def read_restaurants(filename):
with open(filename) as fh:
return [line.rstrip() for line in fh]
Also, since no one has quite clarified this: the reason your original approach doesn't work is that line.strip() returns a modified version of line, but it doesn't alter line:
>>> line = 'hello there\n'
>>> print(repr(line))
'hello there\n'
>>> line.strip()
'hello there'
>>> print(repr(line))
'hello there\n']
So whenever you call stringVar.strip(), you need to do something with the output - build a list, like above, or store it in a variable, or something like that.
You can replace your regular for loop with list comprehension and you don't have to pass '\n' as an argument since strip() method removes leading and trailing white characters by default:
contents_list = [line.strip() for line in contents_list]
You are right: you will need a new list. Also, probably you want to use rstrip() instead of strip():
def read_restaurants(file_name):
file = open(file_name, 'r')
contents_list = file.readlines()
file.close()
new_contents_list = [line.rstrip('\n') for line in contents_list]
return new_contents_list
Then you can do the following:
print(read_restaurants('restaurant.list'))

Removing the first word in each line in python

My Text file currently looks like this:
1 1.094141 -19.991062 -0.830169
2 0.506693 -19.613609 -2.876364
3 -0.355470 -18.932575 -4.884786
4 -0.354663 -27.707542 -21.295307
5 1.008405 -18.191206 -4.542386
6 2.663746 -19.178164 -5.195459
10 0.245458 -17.983212 -2.999652
11 1.411953 -20.360981 -4.684113
I need a program to remove the first character from each line to make it look like:
1.094141 -19.991062 -0.830169
0.506693 -19.613609 -2.876364
-0.355470 -18.932575 -4.884786
-0.354663 -27.707542 -21.295307
1.008405 -18.191206 -4.542386
2.663746 -19.178164 -5.195459
0.245458 -17.983212 -2.999652
1.411953 -20.360981 -4.684113
How do I do this in Python? I have more than 200 files with a similar data and I need to delete the first character. Please help me with the code. Thank you! :)
Well, I am also trying to do other things but I want to fix the logic in this code of mine.
import numpy as np
with open('test2.txt') as f1:
lines = f1.readlines()
with open('test2.txt') as infile:
with open('Output.txt', 'a') as outfile:
outfile.write('# vtk Datafile Version 3.0 \n')
outfile.write('Unstructured Grid.. \n')
outfile.write('ASCII\n')
copy = False
for line in infile:
if line.strip() == "651734":
copy = True
elif line.strip() == "$EndNodes":
copy = False
elif line.strip() == "3089987":
copy = True
elif copy:
outfile.write(line)
The following lines will split the lines you're fed to the lines variable on line 4 of your code, and remove the word that comes before the first space.
for line, i in enumerate(lines):
lines[i] = line.split(" ", 1)[1]
Keep in mind that this will only work if your line always follows the layout you outlined above.
Read up on how to use split properly here
and, of course, study the python documents again carefully.
Having said that, it also looks like the second with open(test2.txt) is superfluous; you have stored the lines of that file in your lines variable on line 4 already, so right there you're just wasting space and memory.
You should probably sketch out your idea again, before you continue writing your program. Right now it's quite redundant and not very well thought through.
The above code is almost correct but not exactly accurate. The code tries to use "line" as an iterator instead of "i."
for i, line in enumerate(lines):
lines[i] = line.split(" ", 1)[1]

Resources