Remove that extra line (called a newline) when printing in python3 - python-3.x

I'm new bee in python 3 and stuck here to remove \n while compiling code as given below, want to return two random lines with out printing \n and w/o square bracket [ ], what should i do?
code is
import random
def head():
f = open("quotes.txt")
quotes = f.readlines()
f.close()
last=18
print(random.sample(quotes,2))
if __name__== "__main__":
head()
And executed this file the result returned as selected two random lines it is fine for me, but in the format like this included \n
['IMPOSSIBLE says itself I M POSSIBLE\n', 'Never stops to Learning till dead end\n']

You are getting results like ['IMPOSSIBLE says itself I M POSSIBLE\n', 'Never stops to Learning till dead end\n'] is because it is list and you directly printing list as it is.
Solution
Remove print(random.sample(quotes,2)) and add following code
tmp = random.sample(quotes,2)
for i in tmp:
print(i,end="")
This will solve your problem and end in print is because your quotes already has newline so we are preventing print from inserting extra \n.

It's resolved!!!
I ran the code by typing command python which it was taken as python 2.7 and returned as this type of junk result, but it works fine as executed with python3 command.

Related

How to read \n as part of text if it is stored in CSV format

I've set delimiter="|" and newline="\n" but when I read a text the \n in the text does not give me a new line on printing. For example:
"Good Morning \nHow are you?"|"Its been a while since we met."
When I take the objects as elements of a list through csv.reader
with open ('file.csv', 'r', newline="\n") as f:
r = csv.reader(f, delimiter='|')
List = []
for lines in r:
List.append(lines)
The List would look like this
["Good Morning \nHow are you?","Its been a while since we met."]
and if I run the code
for i in list:
print i
The expected output of the elements would be
Good Morning
How are you?
Its been a while since we met.
but what I end up getting is
Good Morning \nHow are you?
Its been a while since we met.
Whereas if I directly assigned List=["Good Morning \nHow are you?","Its been a while since we met."]
I do not get this problem. Is there any workaround to this?
I need to use both CSV and \n in the text.

GNU Parallel with Python Script - command line variables not working

This is the first time I am trying to do python execution in GNU parallel.
I have the below python script. I am trying to run it in parallel with a text.txt document loading the variables. The text document has the variables one on each line.
I execute the below script with this code:
parallel --bar -a PairNames.txt python3 CreateDataTablePythonScriptv2.py
Here is the python script being executed:
import sqlite3
import sys
PairName = sys.argv[1]
print(PairName)
DTBLocation = '//mnt//c//Users//Jonathan//OneDrive - Mazars in Oman//Trading//Systems//FibMatrix//Testing Trade Analysis//SQLite//Trade Analysis.db
connection = sqlite3.connect(DTBLocation)
cursor = connection.cursor()
TableName = PairName+'_DATA'
print(TableName)
cursor.execute("""CREATE TABLE IF NOT EXISTS {}
(
Date_Time INTEGER,
Open REAL,
Max_60m_Box REAL
)""".format(TableName))
connection.commit()
connection.close()
It executes correctly the first variable just fine. But the remainder of the variables do print correctly from the print command for the PairName, but for print(TableName) I get the below displays:
GBPUSD
_DATAD
USDCHF
_DATAF
NZDJPY
_DATAY
Its weird to me that it prints the PairName just fine and correctly, but then the PairName does not show up when concating the TableName.
Also, its weird that an extra letter gets added to the end of DATA for each one. It appears that the extra letter at the end of the DATA is the last letter of the input variable. I don't know why its choping the 5 letters off and how it puts it at the end of the DATA.
I printed the tablename.
I watched this video at https://www.youtube.com/watch?v=OpaiGYxkSuQ&ab_channel=OleTange[^]
I tried moving the TableName concat to right under the PairName
I printed the type of the PairName, and it is a string
I tried seperating the varibales in the txt document by tabs and commas instead of next line
I tried assigning the "_DATA" to a variable and then concating the two objects. But it had same result:
TableEnd = '_DATA'
TableName = PairName + TableEnd
If I remove the concat of PairName+'_DATA' and just use PairName only as the TableName, then it works correctly.
Sorry if this is a simple answer, but I cannot figure it out and especially since there is not too much documentation / tutorials for a newbie on GNU Parallel in this situation. Thanks for the help!
The input file is not in DOS format (i.e. ends in a CRLF rather than just an LF)? I checked this using the FILE command:
$ file test.txt
test.txt: ASCII text, with CRLF line terminators
$
Since it was CRLF (DOS format), I converted it using tr:
Copy Codetr -d '\r' < input.file > output.file```

I try to sum all numbers in a txt file, putting two workable variables in one line and it returns 0. What's gone wrong?

I used 3 lines of codes which worked well. Then I try to contract them into one line, which I believe can be done by putting two variables together. But for some reason, the contracted codes only returned 0 instead of the actual sum that can be computed before. What's gone wrong in the contracted codes?
hand = open('xxxxxx.txt')
# This is a text file that contains many numbers in random positions
import re
num = re.findall('[0-9]+', hand.read())
# I used regular expression on variable 'num' to extract all numbers from the file and put them into a list
numi = [int(i) for i in num]
# I used variable 'numi' to convert all numbers in string form to integer form
print(sum(numi))
# Successfully printed out the sum of all integers
print(sum([int(i) for i in re.findall('[0-9]+', hand.read())]))
# Here is the problem. I attempted to contract variables 'num' and 'numi' into one line of codes. But I only got 0 instead of the actual sum from it`enter code here`
if you execute all the code like I see up there, it is normal to get 0 because you didn't re-open the file after using it the first time, just re-open the file "hand" or leave the final line that you want to use and delete the three lines before it.
This code works fine for me -
hand = open('xxxxx.txt')
import re
print(sum([int(i) for i in re.findall('[0-9]+', hand.read())]))
You have to close the file and reopen it before running the last line.

Using for loop to strip white space and resetting the pointer prior to reading a file

I'm using Pycharm and have been very happy so far. However, today I ran into a issue that I can't figure out or explain. The code will prompt the user for an input file. The file is a .txt file that contains lines of words. After the user provides the filename, the program will open it, remove white spaces at the end of the lines and print the contents of the file. (lots_of_words.txt = example)
INPUT
print(lots_of_words.txt)
OUTPUT
Programming is fun and will save the world from errors! ....
Here is the part of the code that is causing the confusion:
user_input = input('Enter the file name: ')
open_file = open(user_input)
for line in open_file:
line = line.rstrip()
read_file = open_file.read()
print(read_file)
OUTPUT
Process finished with exit code 0
Now by just removing the for loop with string.rstrip(), the text file prints fine:
INPUT
user_input = input('Enter the file name: ')
open_file = open(user_input)
# Removed for loop
read_file = open_file.read()
print(read_file)
OUTPUT
Programming is fun and will save the world from errors! ....
I'm using python 3.4 with Pycharm IDE. I realize that the script completed fine without errors, but why won't it print the final variable? I'm sure this is a simple answer, but I can't figure it out.
Running the same code in Python 2.7, prints fine even with string.rstrip().
It has nothing to do with PyCharm.
Your for moves the pointer to the end of the file. To use open_file again, use seek(0), before printing.
open_file = open(user_input)
for line in open_file:
line = line.rstrip()
open_file.seek(0)
read_file = open_file.read()
print(read_file)
Not the most efficient solution though (if efficiency matters in given situation), since you read all the lines twice. You can either store each line after reading it (as suggested in the other answer), or print each line after striping it.
Also, rstrip() will remove whitespaces at the end of the string, but not '\n'.
Irrelevant: You should use with open() as.. : instead of open() since it closes the file automatically.
Iterating over your file object in the for loop will consume it, so there will be nothing left to read, you're simply discarding all lines.
If you want to strip all whitespace from all lines, you could use:
user_input = input('Enter the file name: ')
open_file = open(user_input)
lines = []
for line in open_file:
lines.append(line.rstrip())
print(''.join(lines))
or even shorter:
print(''.join(line.rstrip() for line in open_file))

Python code to read first 14 characters, uniquefy based on them, and parse duplicates

I have a list of more than 10k os string that look like different versions of this (HN5ML6A02FL4UI_3 [14 numbers or letters_1-6]), where some are duplicates except for the _1 to _6.
I am trying to find a way to list these and remove the duplicate 14 character (that comes before the _1-_6).
Example of part of the list:
HN5ML6A02FL4UI_3
HN5ML6A02FL4UI_1
HN5ML6A01BDVDN_6
HN5ML6A01BDVDN_1
HN5ML6A02GVTSV_3
HN5ML6A01CUDA2_1
HN5ML6A01CUDA2_5
HN5ML6A02JPGQ9_5
HN5ML6A02JI8VU_1
HN5ML6A01AJOJU_5
I have tried versions of scripts using Reg Expressions: var n = /\d+/.exec(info)[0]; into the following that were posted into my previous question. and
I also used a modified version of the code from : How can I strip the first 14 characters in an list element using python?
More recently I used this script and I am still not getting the correct output.
import os, re
def trunclist('rhodopsins_play', 'hope4'):
with open('rhodopsins_play','r') as f:
newlist=[]
trunclist=[]
for line in f:
if line.strip().split('_')[0] not in trunclist:
newlist.append(line)
trunclist.append(line.split('_')[0])
print newlist, trunclist
# write newlist to file, with carriage returns
with open('hope4','w') as out:
for line in newlist:
out.write(line)
My inputfile.txt contains more than 10k of data which looks like the list above, where the important part are the characters are in front of the '_' (underscore), then outputting a file of the uniquified ABCD12356_1.
Can someone help?
Thank you for your help
Import python and run this script that is similar to the above. It is slitting at the '_' This worked on the file
def trunclist(inputfile, outputfile):
with open(inputfile,'r') as f:
newlist=[]
trunclist=[]
for line in f:
if line.strip().split('_')[0] not in trunclist:
newlist.append(line)
trunclist.append(line.split('_')[0])
print newlist, trunclist
# write newlist to file, with carriage returns
with open(outputfile,'w') as out:
for line in newlist:
out.write(line)

Resources