Reading a file without newlines
在python中,调用
1 | temp = open(filename,'r').readlines() |
生成一个列表,其中每个元素都是文件中的一行。它有点愚蠢,但仍然如此:
您可以使用
1 | temp = file.read().splitlines() |
或者,您可以手动剥去换行符:
1 | temp = [line[:-1] for line in file] |
注意:最后一个解决方案仅在文件以换行符结尾时有效,否则最后一行将丢失一个字符。
这种假设在大多数情况下都是正确的(尤其是对于文本编辑器创建的文件,文本编辑器通常会添加一个结束换行符)。
如果要避免这种情况,可以在文件末尾添加新行:
1 2 3 4 5 6 7 8 9 10 | with open(the_file, 'r+') as f: f.seek(-1, 2) # go at the end of the file if f.read(1) != ' ': # add missing newline if not already present f.write(' ') f.flush() f.seek(0) lines = [line[:-1] for line in f] |
或者更简单的替代方法是用换行符来代替
1 2 | [line.rstrip(' ') for line in file] |
甚至,虽然很难辨认:
1 2 | [line[:-(line[-1] == ' ') or len(line)+1] for line in file] |
它利用了这样一个事实:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 |
由于
注:对于
1 2 | temp = open(filename,'r').read().split(' ') |
1 | temp = open(filename,'r').read().splitlines() |
另一个例子:
一次读取一行文件。从字符串的末尾删除不需要的字符
1 2 3 4 | with open(filename, 'r') as fileobj: for row in fileobj: print( row.rstrip(' ') ) |
另见
(Python >=2)
我认为这是最好的选择。
试试这个:
1 2 3 4 | u=open("url.txt","r") url=u.read().replace(' ','') print(url) |
1 2 3 4 5 6 | import csv with open(filename) as f: csvreader = csv.reader(f) for line in csvreader: print(line[0]) |
1 2 3 4 5 6 7 8 | my_file = open("first_file.txt","r") for line in my_file.readlines(): if line[-1:] ==" ": print(line[:-1]) else: print(line) my_file.close() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | def getText(): file=open("ex1.txt","r"); names=file.read().split(" "); 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; |