Trying to read a data from another file in python - 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)

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")

Python readlines() function ignores line written by program

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

Replace Carriage Return (CR) and Carriage Return and Line Feed (CRLF) python

I import a .csv file that looks like:
by using the following code:
filetoread = 'G:/input.csv'
filetowrite = 'G:/output.csv'
# https://stackoverflow.com/questions/17658055/how-can-i-remove-carriage-return-from-a-text-file-with-python/42442131
with open(filetoread, "rb") as inf:
with open(filetowrite, "wb") as fixed:
for line in inf:
# line = line.replace('\r\r\n', 'r\n')
fixed.write(line)
print(line)
Which give the output:
b'\xef\xbb\xbfHeader1;Header2;Header3;Header4;Header5;Header6;Header7;Header8;Header9;Header10;Header11;Header12\r\n'
b';;;1999-01-01;;;01;;;;;;\r\n'
b';;;2000-01-01;;;12;;"NY123456789\r\r\n'
b'";chapter;2020-01-01 00:00:00;PE\r\n'
b';;;2020-01-01;;;45;;"NY123456789\r\r\n'
b'";chapter;1900-01-01 00:00:00;PE\r\n'
b';;;1999-01-01;;;98;;;;;;\r\n'
I have issues to replace \r\r\n to \r\n which I guess I need to do to get my desired output.
The error I get when I try to replace the \r\r\n is:
Traceback (most recent call last):
File "g:/till_format_2.py", line 10, in <module>
line = line.replace('\r\r\n', 'r\n')
TypeError: a bytes-like object is required, not 'str'
My desired output:
What do I need to add or change to the code to achieve my desired output?
As the error message says, supply a bytes object.
line = line.replace(b'\r\r\n', b'\r\n')
To get the desired output
line = line.replace(b'\r\r\n', b'')

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')

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