问题
In Python, calling
temp = open(filename,\'r\').readlines()
results in a list in which each element is a line in the file. It\'s a little stupid but still: readlines()
also writes newline character to each element, something I do not wish to happen.
How can I avoid it?
回答1:
You can read the whole file and split lines using str.splitlines:
temp = file.read().splitlines()
Or you can strip the newline by hand:
temp = [line[:-1] for line in file]
Note: this last solution only works if the file ends with a newline, otherwise the last line will lose a character.
This assumption is true in most cases (especially for files created by text editors, which often do add an ending newline anyway).
If you want to avoid this you can add a newline at the end of file:
with open(the_file, 'r+') as f:
f.seek(-1, 2) # go at the end of the file
if f.read(1) != '\n':
# add missing newline if not already present
f.write('\n')
f.flush()
f.seek(0)
lines = [line[:-1] for line in f]
Or a simpler alternative is to strip
the newline instead:
[line.rstrip('\n') for line in file]
Or even, although pretty unreadable:
[line[:-(line[-1] == '\n') or len(line)+1] for line in file]
Which exploits the fact that the return value of or
isn't a boolean, but the object that was evaluated true or false.
The readlines
method is actually equivalent to:
def readlines(self):
lines = []
for line in iter(self.readline, ''):
lines.append(line)
return lines
# or equivalently
def readlines(self):
lines = []
while True:
line = self.readline()
if not line:
break
lines.append(line)
return lines
Since readline()
keeps the newline also readlines()
keeps it.
Note: for symmetry to readlines()
the writelines() method does not add ending newlines, so f2.writelines(f.readlines())
produces an exact copy of f
in f2
.
回答2:
temp = open(filename,'r').read().split('\n')
回答3:
another example:
Reading file one row at the time. Removing unwanted chars with from end of the string str.rstrip(chars)
with open(filename, 'r') as fileobj:
for row in fileobj:
print( row.rstrip('\n') )
see also str.strip([chars])
and str.lstrip([chars])
(python >= 2.0)
回答4:
temp = open(filename,'r').read().splitlines()
回答5:
I think this is the best option.
temp = [line.strip() for line in file.readlines()]
回答6:
Try this:
u=open("url.txt","r")
url=u.read().replace('\n','')
print(url)
回答7:
import csv
with open(filename) as f:
csvreader = csv.reader(f)
for line in csvreader:
print(line[0])
回答8:
To remove all leading and trailing whitespaces (inspired from Абага's Answer) -
temp = [line.strip() for line in open("filename")]
To remove all trailing whitspaces including the newline -
temp = [line.rstrip() for line in open("filename")]
If you just want to removes the trailing newline character and not the whitespaces -
temp = [line.rstrip('\r\n') for line in open("filename")]
P.S. If you find it helpful then please upvote him as well.
回答9:
my_file = open("first_file.txt", "r")
for line in my_file.readlines():
if line[-1:] == "\n":
print(line[:-1])
else:
print(line)
my_file.close()
回答10:
def getText():
file=open("ex1.txt","r");
names=file.read().split("\n");
for x,word in enumerate(names):
if(len(word)>=20):
return 0;
print "length of ",word,"is over 20"
break;
if(x==20):
return 0;
break;
else:
return names;
def show(names):
for word in names:
len_set=len(set(word))
print word," ",len_set
for i in range(1):
names=getText();
if(names!=0):
show(names);
else:
break;
来源:https://stackoverflow.com/questions/12330522/how-to-read-a-file-without-newlines