Print multiple lines without space between lines - python
I have a list of lines (from a text file) to be printed in terminal. This is the format I like (without empty lines between printed lines):
>>> print("line \n" * 5)
line
line
line
line
line
This is how it looks (a line with text, an empty line, etc.):
>>> for x in range(0, 5): print "line \n"
...
line
line
line
line
line
Any idea why it's working in this way and how to print my list of lines without empty lines between them?
UPDATE (this is where I want to get rid of empty lines):
with open(FILE, 'r') as f:
lines = f.readlines()
for line in lines:
print line
This is actually due to the way you're reading the file. If you've done something like
with open(FILE) as f:
data = f.readlines()
Then the data will be a list of lines which retain the end of line character. If you don't want the end of line character, use this instead:
with open(FILE) as f:
data = f.read().splitlines()
If you don't want to change the way that you read the data into a list, then concatenate and print the lines like this instead:
print ''.join(data)
To answer the literal question, if you have a string with a newline, and you want to suppress the newline generated by the print statement, the way to do that in Python 2 is by using a trailing comma on the print statement:
with open(FILE) as f:
for line in f:
print line,
But note, that's not really necessary to iterate line by line like that. You may as well just print the data directly:
with open(FILE) as f:
print f.read()
When using a for loop you can remove "\n" as follows
for x in range(0, 5): print "line"
The print command implicitly adds a new line feed \n in the output display. Remove the \n to avoid printing blank lines in the looping structure.
print adds a trailing newline by default. You can disable it as follows:
from __future__ import print_function # only needed for python 2
print("string", end="")
By default print adds a newline, and your strings also have it; you have two possible solutions.
Either override this behaviour, setting the string to be put to empty:
# python 3.*
for x in range(0, 5): print("line \n", end="")
And
# python 2.*
from __future__ import print_function # to use py3 print in py2
for x in range(0, 5): print("line \n", end="")
Alternatively, if you don't have full control over the lines - some may have the newlines, other - not, trim any newline endings and leave the default behaviour:
for x in range(0, 5): print("line \n".rstrip("\n").rstrip("\r")) # takes care of also Windows line ending, just in case
A standard call to the print function will add a newline automatically so you can either remove the \n from your existing line(s), if the lines come from an external file use line.strip(), or tell print not to add the newline with: print(line, end='')
This will work for Python3 or for 2.7 with from __future__ import print_function as the first code line.
Related
How do I print only the first instance of a string in a text file using Python?
I am trying to extract data from a .txt file in Python. My goal is to capture the last occurrence of a certain word and show the next line, so I do a reverse () of the text and read from behind. In this case, I search for the word 'MEC', and show the next line, but I capture all occurrences of the word, not the first. Any idea what I need to do? Thanks! This is what my code looks like: import re from file_read_backwards import FileReadBackwards with FileReadBackwards("camdex.txt", encoding="utf-8") as file: for l in file: lines = l while line: if re.match('MEC', line): x = (file.readline()) x2 = (x.strip('\n')) print(x2) break line = file.readline() The txt file contains this: MEC 29/35 MEC 28,29/35 And with my code print this output: 28,29/35 29/35 And my objetive is print only this: 28,29/35
This will give you the result as well. Loop through lines, add the matching lines to an array. Then print the last element. import re with open("data\camdex.txt", encoding="utf-8") as file: result = [] for line in file: if re.match('MEC', line): x = file.readline() result.append(x.strip('\n')) print(result[-1])
Get rid of the extra imports and overhead. Read your file normally, remembering the last line that qualifies. with ("camdex.txt", encoding="utf-8") as file: for line in file: if line.startswith("MEC"): last = line print(last[4:-1]) # "4" gets rid of "MEC "; "-1" stops just before the line feed. If the file is very large, then reading backwards makes sense -- seeking to the end and backing up will be faster than reading to the end.
How to concatenate a string in python?
I try to read in a file and output in a single line. File: how are you code: infile = open('input', 'r') for line in infile: line = line.rstrip('\n') print (line) rstrip already strip off '\n', however the output still spread into 3 lines. how are you How to make the print out into single line?
Just pass empty string to end parameter in print function after strippping off the newline character. print (line, end = "") print by default print the content in a new line for each iteration but by passing empty string to the end parameter, this default behaviour won't work. If you failed to remove the newline character, it would print the content along with the newline character.
Because the print() function is being called independently each time the loop runs. And every time the print runs, the output is started to be printed on a new line.
The title asks for concatenation but the details just ask for output. The print answers deals with the latter but if you want to concatenate, then you would use join or + >>> with open('input', 'r') as infile: ... output = "" ... for line in infile: ... output += line.rstrip('\n') ... print(output) howareyou However, given you likely want a space between the strings then I would suggest you look into join, which can simply be used in conjunction with a comprehension: >>> with open('input', 'r') as infile: ... print(" ".join(line.rstrip(`\n`) for line in infile)) how are you
If you use python 2.7, the following syntax should work: print line,
to make 2&3 compatible, you can: from __future__ import print_function print('hello, world', end='') so your code could be: from __future__ import print_function infile = open('input', 'r') for line in infile: line = line.rstrip('\n') print(line, end='') or this one: with open('input') as f: lines = [line.strip() for line in f.readlines()] print(' '.join(lines))
\n appending at the end of each line
I am writing lines one by one to an external files. Each line has 9 columns separated by Tab delimiter. If i split each line in that file and output last column, i can see \n being appended to the end of the 9 column. My code is: #!/usr/bin/python with open("temp", "r") as f: for lines in f: hashes = lines.split("\t") print hashes[8] The last column values are integers, either 1 or 2. When i run this program, the output i get is, ['1\n'] ['2\n'] I should only get 1 or 2. Why is '\n' being appended here? I tried the following check to remove the problem. with open("temp", "r") as f: for lines in f: if lines != '\n': hashes = lines.split("\t") print hashes[8] This too is not working. I tried if lines != ' '. How can i make this go away? Thanks in advance.
Try using strip on the lines to remove the \n (the new line character). strip removes the leading and trailing whitespace characters. with open("temp", "r") as f: for lines in f.readlines(): if lines.strip(): hashes = lines.split("\t") print hashes[8]
\n is the newline character, it is how the computer knows to display the data on the next line. If you modify the last item in the array hashes[-1] to remove the last character, then that should be fine.
Depending on the platform, your line ending may be more than just one character. Dos/Windows uses "\r\n" for example. def clean(file_handle): for line in file_handle: yield line.rstrip() with open('temp', 'r') as f: for line in clean(f): hashes = line.split('\t') print hashes[-1] I prefer rstrip() for times when I want to preserve leading whitespace. That and using generator functions to clean up my input.
Because each line has 9 columns, the 8th index (which is the 9th object) has a line break, since the next line starts. Just take that away: print hashes[8][:-1]
Splitting lines in python based on some character
Input: !,A,56281,12/12/19,19:34:12,000.0,0,37N22.714,121W55.576,+0013!,A,56281,12/1 2/19,19:34:13,000.0,0,37N22.714,121W55.576,+0013!,A,56281,12/12/19,19:34:14,000. 0,0,37N22.714,121W55.576,+0013!,A,56281,12/12/19,19:34:15,000.0,0,37N22.714,121W 55.576,+0013!,A,56281,12/12/19,19:34:16,000.0,0,37N22.714,121W55.576,+0013!,A,56 281,12/12/19,19:34:17,000.0,0,37N22.714,121W55.576,+0013!,A,56281,12/12/19,19:34 :18,000.0,0,37N22.714,121W55.576,+0013!,A,56281,12/12/19,19:34:19,000.0,0,37N22. Output: !,A,56281,12/12/19,19:34:12,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:13,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:14,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:15,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:16,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:17,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:18,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:19,000.0,0,37N22. '!' is the starting character and +0013 should be the ending of each line (if present). Problem which I am getting: Output is like : !,A,56281,12/12/19,19:34:12,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/1 2/19,19:34:13,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:14,000. 0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:15,000.0,0,37N22.714,121W Any help would be highly appreciated...!!! My code: file_open= open('sample.txt','r') file_read= file_open.read() file_open2= open('output.txt','w+') counter =0 for i in file_read: if '!' in i: if counter == 1: file_open2.write('\n') counter= counter -1 counter= counter +1 file_open2.write(i)
You can try something like this: with open("abc.txt") as f: data=f.read().replace("\r\n","") #replace the newlines with "" #the newline can be "\n" in your system instead of "\r\n" ans=filter(None,data.split("!")) #split the data at '!', then filter out empty lines for x in ans: print "!"+x #or write to some other file .....: !,A,56281,12/12/19,19:34:12,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:13,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:14,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:15,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:16,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:17,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:18,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:19,000.0,0,37N22.
Could you just use str.split? lines = file_read.split('!') Now lines is a list which holds the split data. This is almost the lines you want to write -- The only difference is that they don't have trailing newlines and they don't have '!' at the start. We can put those in easily with string formatting -- e.g. '!{0}\n'.format(line). Then we can put that whole thing in a generator expression which we'll pass to file.writelines to put the data in a new file: file_open2.writelines('!{0}\n'.format(line) for line in lines) You might need: file_open2.writelines('!{0}\n'.format(line.replace('\n','')) for line in lines) if you find that you're getting more newlines than you wanted in the output. A few other points, when opening files, it's nice to use a context manager -- This makes sure that the file is closed properly: with open('inputfile') as fin: lines = fin.read() with open('outputfile','w') as fout: fout.writelines('!{0}\n'.format(line.replace('\n','')) for line in lines)
Another option, using replace instead of split, since you know the starting and ending characters of each line: In [14]: data = """!,A,56281,12/12/19,19:34:12,000.0,0,37N22.714,121W55.576,+0013!,A,56281,12/1 2/19,19:34:13,000.0,0,37N22.714,121W55.576,+0013!,A,56281,12/12/19,19:34:14,000. 0,0,37N22.714,121W55.576,+0013!,A,56281,12/12/19,19:34:15,000.0,0,37N22.714,121W 55.576,+0013!,A,56281,12/12/19,19:34:16,000.0,0,37N22.714,121W55.576,+0013!,A,56 281,12/12/19,19:34:17,000.0,0,37N22.714,121W55.576,+0013!,A,56281,12/12/19,19:34 :18,000.0,0,37N22.714,121W55.576,+0013!,A,56281,12/12/19,19:34:19,000.0,0,37N22.""".replace('\n', '') In [15]: print data.replace('+0013!', "+0013\n!") !,A,56281,12/12/19,19:34:12,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:13,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:14,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:15,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:16,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:17,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:18,000.0,0,37N22.714,121W55.576,+0013 !,A,56281,12/12/19,19:34:19,000.0,0,37N22.
Just for some variance, here is a regular expression answer: import re outputFile = open('output.txt', 'w+') with open('sample.txt', 'r') as f: for line in re.findall("!.+?(?=!|$)", f.read(), re.DOTALL): outputFile.write(line.replace("\n", "") + '\n') outputFile.close() It will open the output file, get the contents of the input file, and loop through all the matches using the regular expression !.+?(?=!|$) with the re.DOTALL flag. The regular expression explanation & what it matches can be found here: http://regex101.com/r/aK6aV4 After we have a match, we strip out the new lines from the match, and write it to the file.
Let's try to add a \n before every "!"; then let python splitlines :-) : file_read.replace("!", "!\n").splitlines()
I will actually implement as a generator so that you can work on the data stream rather than the entire content of the file. This will be quite memory friendly if working with huge files >>> def split_on_stream(it,sep="!"): prev = "" for line in it: line = (prev + line.strip()).split(sep) for parts in line[:-1]: yield parts prev = line[-1] yield prev >>> with open("test.txt") as fin: for parts in split_on_stream(fin): print parts ,A,56281,12/12/19,19:34:12,000.0,0,37N22.714,121W55.576,+0013 ,A,56281,12/12/19,19:34:13,000.0,0,37N22.714,121W55.576,+0013 ,A,56281,12/12/19,19:34:14,000.0,0,37N22.714,121W55.576,+0013 ,A,56281,12/12/19,19:34:15,000.0,0,37N22.714,121W55.576,+0013 ,A,56281,12/12/19,19:34:16,000.0,0,37N22.714,121W55.576,+0013 ,A,56281,12/12/19,19:34:17,000.0,0,37N22.714,121W55.576,+0013 ,A,56281,12/12/19,19:34:18,000.0,0,37N22.714,121W55.576,+0013 ,A,56281,12/12/19,19:34:19,000.0,0,37N22.
Problem with replacing a word in a file, using Python
I have a .txt file containing data like this: 1,Rent1,Expense,16/02/2010,1,4000,4000 1,Car Loan1,Expense,16/02/2010,2,4500,9000 1,Flat Loan1,Expense,16/02/2010,2,4000,8000 0,Rent2,Expense,16/02/2010,1,4000,4000 0,Car Loan2,Expense,16/02/2010,2,4500,9000 0,Flat Loan2,Expense,16/02/2010,2,4000,8000 I want to replace the first item. If it is 1, means it should remain the same but if it is 0 means I want to change it to 1. So I have tried using the following code: import fileinput for line in fileinput.FileInput("sample.txt",inplace=1): s=line.split(",") print a print ','.join(s) But after successfully executed the program my .txt file looks like: 1,Rent1,Expense,16/02/2010,1,4000,4000 1,Car Loan1,Expense,16/02/2010,2,4500,9000 1,Flat Loan1,Expense,16/02/2010,2,4000,8000 0,Rent2,Expense,16/02/2010,1,4000,4000 0,Car Loan2,Expense,16/02/2010,2,4500,9000 0,Flat Loan2,Expense,16/02/2010,2,4000,8000 Now I want to remove the empty line. Is it possible, or is there any other way to replace the 0's?
print adds an extra newline after the input and you already have one newline there. You should either strip the existing newline (line.rstrip("\n")) or use sys.stdout.write() instead.
import fileinput import re p = re.compile(r'^0,') for line in fileinput.FileInput("sample.txt",inplace=1): print p.sub('1,', line.strip()) The existing code you have doesn't actually change the lines like you want; print a doesn't do anything if a isn't actually defined! So you end up just printing a blank line (the print a bit) and then printing the existing line, hence why you get a file that's unaltered except for the addition of some blank lines.
Either use rstrip to remove the trailing new lines before printing or use sys.stdout.write instead of print. Also, if you only need to modify the first element, there is no need to split the entire line and join it again. You only need to split on the first comma: line.split(',', 1) If you want even better performance you could also just test the value of line[0] directly.
fixed = [] for l in file('sample.txt'): parts = l.split(',',1) if(parts[0] == '0'): # not sure what you want to do here, but you want to "change this" number to 1? parts[0] = 1 fixed.append(parts.join(',')) outp = file('sample.txt','w') for f in fixed: outp.write(f) outp.close() This is untested, but it should get you most of the way there. Good luck
import fileinput for line in fileinput.FileInput("sample.txt",inplace=1): s=line.rstrip().split(",") print a print ','.join(s)
You have to use a comma at the end of your print so that it doesn't add a newline. Like so: print "Hello", This is what I came up with: input = open('file.txt', 'r') output = open('output.txt', 'w') for line in input: values = line.split(',') if (values[0] == '0'): values[0] = '1' output.write(','.join(values)) If you want a better csv handling library you might want to use this instead of split.
The cleanest way to do it is to use the CSV parser : import fileinput import csv f = fileinput.FileInput("test.txt",inplace=1) fichiercsv = csv.reader(f, delimiter=',') for line in fichiercsv: line[0] = "1" print ",".join(line)