Python readlines() function ignores line written by program - python

I want to read lines and check whether an specific number is in it, but when reading and printing the list with the lines I can't get the 1st line where my testing string was written by the same program:
Code I use to write stuff on the file:
with open('db.txt', 'a') as f:
f.write(f'Request's channel id from guild {guild.id}:{request_channel_id} \n')
and the code I'm using to read the files and check the lines is:
with open('db.txt', 'r') as f:
index = 0
for line in f:
index += 1
if str(message.guild.id) in line or str(message.channel.id) in line:
break
content = f.readlines()
print(content)
content = content[index]
content.strip(":")
The second block of code is returning: [] and empty list even though I opened it and the line is there. But, when I write directly at the file with my keyboard the code "sees" the random stuff I wrote.
.txt file content:
Id do canal de request servidor 833434062248869899: 888273958263222332
a.a
all
a
a
a
a
Error:
['a.a\n', '\n', 'all\n', 'a\n', 'a\n', 'a\n', 'a']
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\CARVALHO\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\CARVALHO\desktop\gabriel\codando\music_bot\main.py", line 48, in on_message
request_channel_id = int(content[1])
IndexError: string index out of range

Related

I am unable to create multiple files with this code, what is wrong?

So I'm trying to write a program that takes names from a list and adds it to a letter. A text file is created for each name for the letter however the code seems to stop working at that point.
letter = []
names = []
file = open("Input/Letters/starting_letter.txt", "r")
letter = file.readlines()
file.close()
name1 = open("Input/Names/invited_names.txt", "r")
names = name1.readlines()
name1.close()
for name in names:
create_letter = open(f"{name}.txt", "w")
for line in letter:
line = line.replace("[name],", f"{name},")
create_letter.write(line)
create_letter.close()
I get the error message
Traceback (most recent call last):
File "C:\Users\Default User\PycharmProjects\Mail Merge Project Start\main.py", line 10, in <module>
create_letter = open(f"{name}.txt", "w")
OSError: [Errno 22] Invalid argument: 'Aang\n.txt'
Is there a problem with the way I am creating the files?
You can't have newlines in your file name. It is invalid in your OS/filesystem.
Remove them with:
open(f"{name.strip()}.txt", "w")
Or:
open(f"{name.replace('\n', '')}.txt", "w")

Trying to read a data from another file in python

I am trying to make my code read the data from a different file. The data in the file emaillist.txt is written in the following format:
a
b
b
c
s
f
s
Now I am tryin to pick a random email from this file and I am getting an error.
Here is the code {Note: this is a piece of code, I have imported the correct libraries}:
with open('emaillist.txt') as emails:
read_emails = csv.reader(emails, delimiter = '\n')
for every_email in read_emails:
return random.choice(every_email)
and this is the error:
Traceback (most recent call last):
File "codeOffshoreupdated.py", line 56, in <module>
'email': email_random(),
File "codeOffshoreupdated.py", line 12, in email_random
for every_email in read_emails:
ValueError: I/O operation on closed file.
Can you please help me fix it? It will be very helpful. Thanks in advance
This code will return you a random email from the emilas that in the file because in your code is returning the first email from the file since it is the first iteration of for every_email in read_emails:
with open('emaillist.txt') as emails:
read_emails = csv.reader(emails, delimiter = '\n')
return random.choice(list(read_emails))[0]
Indent your for loop, like this:
with open('emaillist.txt') as emails:
read_emails = csv.reader(emails, delimiter = '\n')
for every_email in read_emails:
return random.choice(every_email)

Replace String from file In python?

I have a file that contains several Phone Number.
Now I want to convert any line of this file to VCF file.
So,first i defined e template model for VCF file that have a String "THISNUMBER"
And i want to open file (thats have phone numbers) and replace thats lines to Template model (THISNUMBER)
i write this Python code :
template = """BEGIN:VCARD
VERSION:3.0
N:THISNUMBER;;;
FN:THISNUMBER
TEL;TYPE=CELL:THISNUM
END:VCARD"""
inputfile=open('D:/xxx/lst.txt','r')
counter=1
for thisnumber in inputfile:
thisnumber=thisnumber.rstrip()
output=template.replace('THISNUMBER',thisnumber)
outputFile=('D:/xxx/vcfs/%05i.vcf' % counter,'w')
outputFile.write(output)
output.close
print ("writing file %i") % counter
counter +=1
inputfile.close()
But I Give This ERROR :
Traceback (most recent call last):
File "D:\xxx\a.py", line 16, in <module>
outputFile.write(output)
AttributeError: 'tuple' object has no attribute 'write'
I'll write a full fledged answer because I want to address your code style, if that's fine.
The problem is likely that you forgot to call open() on your outputFile. But let me introduce to you a nice way of handling files in Python. This way you don't even have to remember to call close(). It is all done with a context manager. The file is closed when the with statement exits.
template = """BEGIN:VCARD
VERSION:3.0
N:THISNUMBER;;;
FN:THISNUMBER
TEL;TYPE=CELL:THISNUM
END:VCARD"""
with open('D:/xxx/lst.txt', 'r') as inputfile:
counter = 1
for number in inputfile:
number = number.rstrip()
output = template.replace('THISNUMBER', number)
with open('D:/xxx/vcfs/%05i.vcf' % counter, 'w') as outputFile:
outputFile.write(output)
print('writing file %i' % counter)
counter += 1
change
outputFile=('D:/xxx/vcfs/%05i.vcf' % counter,'w')
to
outputFile=open('D:/xxx/vcfs/%05i.vcf' % counter,'w')

Error using langdetect in python: "No features in text"

Hey I have a csv with multilingual text. All I want is a column appended with a the language detected. So I coded as below,
from langdetect import detect
import csv
with open('C:\\Users\\dell\\Downloads\\stdlang.csv') as csvinput:
with open('C:\\Users\\dell\\Downloads\\stdlang.csv') as csvoutput:
writer = csv.writer(csvoutput, lineterminator='\n')
reader = csv.reader(csvinput)
all = []
row = next(reader)
row.append('Lang')
all.append(row)
for row in reader:
row.append(detect(row[0]))
all.append(row)
writer.writerows(all)
But I am getting the error as LangDetectException: No features in text
The traceback is as follows
runfile('C:/Users/dell/.spyder2-py3/temp.py', wdir='C:/Users/dell/.spyder2-py3')
Traceback (most recent call last):
File "<ipython-input-25-5f98f4f8be50>", line 1, in <module>
runfile('C:/Users/dell/.spyder2-py3/temp.py', wdir='C:/Users/dell/.spyder2-py3')
File "C:\Users\dell\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
execfile(filename, namespace)
File "C:\Users\dell\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/dell/.spyder2-py3/temp.py", line 21, in <module>
row.append(detect(row[0]))
File "C:\Users\dell\Anaconda3\lib\site-packages\langdetect\detector_factory.py", line 130, in detect
return detector.detect()
File "C:\Users\dell\Anaconda3\lib\site-packages\langdetect\detector.py", line 136, in detect
probabilities = self.get_probabilities()
File "C:\Users\dell\Anaconda3\lib\site-packages\langdetect\detector.py", line 143, in get_probabilities
self._detect_block()
File "C:\Users\dell\Anaconda3\lib\site-packages\langdetect\detector.py", line 150, in _detect_block
raise LangDetectException(ErrorCode.CantDetectError, 'No features in text.')
LangDetectException: No features in text.
This is how my csv looks like
1)skunkiest smokiest yummiest strain pain killer and mood lifter
2)Relaxation, euphorique, surélevée, somnolence, concentré, picotement, une augmentation de l’appétit, soulager la douleur Giggly, physique, esprit sédation
3)Reduzierte Angst, Ruhe, gehobener Stimmung, zerebrale Energie, Körper Sedierung
4)Calmante, relajante muscular, Relajación Mental, disminución de náuseas
5)重いフルーティーな幸せ非常に強力な頭石のバースト
Please help me with this.
You can use something like this to detect which line in your file is throwing the error:
for row in reader:
try:
language = detect(row[0])
except:
language = "error"
print("This row throws and error:", row[0])
row.append(language)
all.append(row)
What you're going to see is that it probably fails at "重いフルーティーな幸せ非常に強力な頭石のバースト". My guess is that detect() isn't able to 'identify' any characters to analyze in that row, which is what the error implies.
Other things, like when the input is only a URL, also cause this error.
The error occurred when passing an object with no letters to detect. At least one letter should be there.
To reproduce, run any of below commands:
detect('.')
detect(' ')
detect('5')
detect('/')
So, you may apply some text pre-processing first to drop records in which row[0] value is an empty string,a null value, a white space, a number, a special character, or simply doesn't include any alphabets.
the problem is a null text or something like ' ' with no value;
check this in a condition and loop your reader in a list comprehension or
from langdetect import detect
textlang = [detect(elem) for elem in textlist if len(elem) > 50]
textlang = [detect(elem) if len(elem) > 50 else elem == 'no' for elem in textlist]
or with a loop
texl70 = df5['Titletext']
langdet = []
for i in range(len(df5)):
try:
lang=detect(texl70[i])
except:
lang='no'
print("This row throws error:", texl70[i])
langdet.append(lang)
The error occurrs when string has no letters. If you want to ignore that row and continue the process.
for i in df.index:
str = df.iloc[i][1]
try:
lang = detect(str)
except:
continue

reading last line of txt file in python and change it into variable to make calculation

td = 'date of transaction.txt'
tf = 'current balance.txt'
tr = 'transaction record.txt'
for line in open(tf):pass
for line2 in open(td):pass
for line3 in open(tr):pass
print line2,line,line3
"""
so call recall back last record
"""
rd=raw_input('\ndate of transaction: ')
print "Choose a type of transaction to proceed... \n\tA.Withdrawal \n\tB.Deposit \n\tC.Cancel & exit"
slc=raw_input('type of transaction: ')
i=1
while (i>0):
if slc=="A" or slc=="B" or slc=="C":
i=0
else:
i=i+1
slc=raw_input('invalid selection, please choose again...(A/B/C): ')
if slc=="A":
rr=input('\namount of transaction: ')
Line_len = 10 # or however long a line is, since in my example they all looked the same
SEEK_END = 2
file = open(tf, "r")
file.seek(-Line_len, SEEK_END)
a = int(str(file.read(Line_len)).split(" ")[0].strip())
rf=a-rr
f1=open(tf, 'a+')
f1.write('\n'+rf)
f1.close()
d1=open(td, 'a+')
d1.write('\n'+rd)
d1.close
r1=open(tr, 'a+')
r1.write('\n-'+rr)
r1.close
else:
print 'later'
above is my code, the function is to get data(last line) from txt file and read it, get new data and write it to the txt file again by creating new line.
my txt file(current balance.txt) should look like this:
2894.00
2694.00
but when i try to use the last line which is 2694.00 to do calculation(rf=a-rr), it failed returning this error:
Traceback (most recent call last):
File "C:\Python27\acc.py", line 27, in <module>
file.seek(-Line_len, SEEK_END)
IOError: [Errno 22] Invalid argument
else if i use this code:
for line in open(tf):
pass
a = line
rf=a-rr
it return this error:
Traceback (most recent call last):
File "C:\Python27\acc.py", line 27, in <module>
rf=a-rr
TypeError: unsupported operand type(s) for -: 'str' and 'int'
I seriously have no idea why...please help me...
To obtain last line of the file, you can simple do
with open('my_file.txt') as file:
last_line = file.readlines()[-1]
#last_line is a string value pointing to last line, to convert it into float, you can do
number = float(last_line.strip('\n').strip(' '))
The function input is giving you a string. Try doing:
rf=a-float(rr)

Categories

Resources