#๐Ÿ”’ making text file

127 messages ยท Page 1 of 1 (latest)

hybrid void
#

i want to implement a text file which contains atomic weigth data values, that i can use to later calculate weights of molecules. How would i go about this?

winter capeBOT
#

@hybrid void

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

wispy karma
hybrid void
#

both id say

#

how to make it and how to utilise it in my program

wispy karma
#

do you have examples of atomic weights?

hybrid void
#

H = 1.008
O = 15.999
C = 12.11

wispy karma
#

Ok great!

#

If you had this as a string, do you know how you'd split it up into "element" and "value"?

"H = 1.008"

hybrid void
#

through a dictionary?

wispy karma
#

a dictionary would be great to hold the results, but we still need to "parse" the string

#

we need a way to separate the element and weight out because right now it's just a single string

#
atomic = "H = 1.008"
hybrid void
#

ive lowk not seen that before

#

what would this do

wispy karma
#

You haven't seen a string before?

hybrid void
#

i have but not one with two = sings

#

signs*

wispy karma
#

the 2nd equal sign is just part of the string

#

it doesn't mean anything, it's just a literal =

hybrid void
#

oh its in " ic

#

then .split(=) ?

wispy karma
#

exactly

#

you could use whatever symbol you wanted really, as long as your consistent

#

atomic = "H | 1.008"

#

you could do this instead

hybrid void
#

ic

wispy karma
#

atomic = "H|1.008"

#
H|1.008
O|15.999
C|12.11
#

so if you have a text file that looks something like this, we can read the file line by line, split the |, then add a new key/value pair to a dictionary based on that result

hybrid void
#

ok ic

indigo mason
#

colon might look more natural in the text file though

hybrid void
#

how would i make a file?

wispy karma
#

or a comma, if we want to stick with more of a csv format

wispy karma
#

make a new txt file on your computer and fill it in with the info

hybrid void
#

file_path = "new_file.txt"
with open(file_path, 'w') as file:
i read something like this, not examtly sure how it works. reason im asking is because duriong the exam im not sure ill be able to make oneseperately since ill be in a safe exam browser

wispy karma
#

perhaps you'll be provided the file then

hybrid void
#

ic

#

is the with open function just a way of accessing an existing file then?

wispy karma
#

for now, just create the file and then I can show you how to read it

wispy karma
#

open() is the function
with is a keyword for a context manager

hybrid void
#

i see thanks for the help, ill try to complete the rest of the program myself and will just post here if i get stuck

indigo mason
wispy karma
#

TSV it is ๐Ÿ™‚

indigo mason
hybrid void
hybrid void
#

i tried the split method for the textfile but i get an error message when using the (,) for some reason:

with open(atoms_file, 'r') as file:
for line in file:
atom, weight = line.split(,)
atom_weights[atom] = float(weight)

wispy karma
#

strings always need "" around them

forest garden
# hybrid void i have but not one with two = sings

If it's inside the string, so the "", it's just normal text.
The second = does not affect the code at all, think about it as a normal text.

So basically you have a variable, which is atomic and assigned a string/text to it.

#

oh wait

#

smh

#

old message

#

mb gng

hybrid void
#

like in this context

wispy karma
#

split() needs a string as its argument

#

the thing you put inside the () is called an argument

hybrid void
#

oh i thought split meant what character signifies a split to be made

wispy karma
#

it does

#

the character must be a string

hybrid void
#

so is line not an str in this scenario is what u mean?

wispy karma
#

if you want to split using a comma, it should be (",")

#

you had (,)

hybrid void
#

oh ic

#

oh now it works haha thanks

hybrid void
#

ok i think ive finished the calculations part of the program, however i get the error message
FileNotFoundError: [Errno 2] No such file or directory: 'atoms.txt'
when i run the program.

it says the problem is on this line:
with open(atoms_file, 'r') as file:

this is the previous line which im thinking might have something to do with it but im not sure:
atoms_file = "atoms.txt"
any ideas or should i send more of the code?

wispy karma
#

where is the atoms.txt file?

hybrid void
#

like right next to my python file in the vs code folder thingy

#

theyre in the same folder

wispy karma
#

I don't use VSC, but I know it does some strange things regarding your cwd (current working directory)

hybrid void
#

oh so its supposed to work then?

#

just some weird stuff thats specific to vsc

wispy karma
#

yeah, when you launch a program, relative files always need to be relative to your CWD

#

usually it's set to whatever folder the file you're running is in

#

you can force it with a little trick though

#
import os

os.chdir(os.path.dirname(__file__))
#

put this at the top of your file

hybrid void
#

oh sick

#

now im getting keyErros ๐Ÿ˜ญ

#

KeyError: 'H' no idea what this means tbh

wispy karma
#

do you know what a key is?

hybrid void
#

yh the first part of the dict

wispy karma
#

a key error is when you try and look up a key in a dict that doesn't exist

#

!e

empty_dict = {}
print(empty_dict['H'])
winter capeBOT
# wispy karma !e ```py empty_dict = {} print(empty_dict['H']) ```

:x: Your 3.14 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 2, in <module>
003 |     print(empty_dict['H'])
004 |           ~~~~~~~~~~^^^^^
005 | KeyError: 'H'
hybrid void
#

oh ic

wispy karma
#

now it's up to you to figure out why that might be the case

#

print is your best friend for debugging things

#

print out the dict and see why it might be missing that key

hybrid void
#

weird my dict is empty

wispy karma
#

now work backwards

#

add some prints where you would expect to see them

hybrid void
#

im printing right after i first add to them

#

atom_weights[atom] = float(weight) where atom_weights is the dict

wispy karma
#

print out some variables. Always think in your head "I expect it to look like this" and if it doesn't match what you think, you need to work backwards to figure out what might be the issue

wispy karma
#

!paste

winter capeBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

hybrid void
#

import os

os.chdir(os.path.dirname(file))
def m_mass(molecule):
atom_weights = {}
atoms_file = "atoms.txt"
with open(atoms_file, 'r') as file:
for line in file:
atom, weight = line.split(",")
atom_weights[atom] = float(weight)
print (atom_weights)
m_mass('C')

winter capeBOT
#

Hey @hybrid void!

Please edit your message to use a code block

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
wispy karma
#

use the paste link or add the discord markdown so I can properly read your code

hybrid void
#

!paste

winter capeBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

hybrid void
wispy karma
#

can you share the txt file too?

#

my guess is you have a space before/after the comma

#

although that shouldn't result in an empty dict...

rotund vault
wispy karma
#

perhaps you never saved the file

hybrid void
#

!p

winter capeBOT
#
Missing required argument

pep_number

wispy karma
#

yeah, you should only be generating this atom dict once

hybrid void
wispy karma
#

you have = in the file, but you're trying to split using ,

hybrid void
#

oh

#

it was

#

a problem of not savingf

rotund vault
wispy karma
hybrid void
#

yh i changed it to C,numbers

#

and so on

#

oh nice now it works ahhaha finally thanks for all the help

winter capeBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.