Python For Quantum Mechanics#

Week 2: External Data#

from IPython.display import YouTubeVideo
YouTubeVideo('Pjl23pFmk_w',width=700, height=400)

Contents#

User Input#

The input() function can be used to ask for and take in data from the user. Try running the cell below, enter space seperated integers in the field, and then press return.

entry = input('enter space seperated integers: ')
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[2], line 1
----> 1 entry = input('enter space seperated integers: ')

File /opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/ipykernel/kernelbase.py:1281, in Kernel.raw_input(self, prompt)
   1279 if not self._allow_stdin:
   1280     msg = "raw_input was called, but this frontend does not support input requests."
-> 1281     raise StdinNotImplementedError(msg)
   1282 return self._input_request(
   1283     str(prompt),
   1284     self._parent_ident["shell"],
   1285     self.get_parent("shell"),
   1286     password=False,
   1287 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

The data is now stored as a single string called entry. This is not particularly useful for working with this data. We shoud put this data into a list and make each element the integer entered.

l = entry.split()

for i in range(len(l)):
    l[i] = int(l[i])

print(l)
[5, 7, 2]

Remebering what we learened about compactifying our code we can write this all in one line.

l = [int(i) for i in input('enter space seperated integers: ').split()]
print(l)
enter space seperated integers: 5 23 7 453
[5, 23, 7, 453]

Reading from File#

We can open a file for reading and print out its contents with the following syntax.

with open('test.txt','r') as f:
    print(f.read())
Hello!
You are reading this text file.
This file has a number of lines of text.

Also some empty lines.



Thanks for reading!

The file test.txt is stored in the same directory as this notebook to save specifying a path. The 'r' argument in the open function specifies that we are opening this file for reading so this file cannont be editted while open in this way. Within the indented clause the file can be refered to as f.

We can also iterate through the file which will get each line as a string.

with open('test.txt','r') as f:
    for line in f:
        print(line)
Hello!

You are reading this text file.

This file has a number of lines of text.



Also some empty lines.







Thanks for reading!

These lines can also be iterated through as they are strings so we can go letter by letter.

with open('test.txt','r') as f:
    for line in f:
        for letter in line:
            print(letter)
H
e
l
l
o
!


Y
o
u
 
a
r
e
 
r
e
a
d
i
n
g
 
t
h
i
s
 
t
e
x
t
 
f
i
l
e
.


T
h
i
s
 
f
i
l
e
 
h
a
s
 
a
 
n
u
m
b
e
r
 
o
f
 
l
i
n
e
s
 
o
f
 
t
e
x
t
.




A
l
s
o
 
s
o
m
e
 
e
m
p
t
y
 
l
i
n
e
s
.








T
h
a
n
k
s
 
f
o
r
 
r
e
a
d
i
n
g
!

Writing to File#

Let’s say we want to store a list of the first 11 sqaure numbers. First it might be good to make such a list.

l = [i**2 for i in range(11)]

print(l)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Now we want to store this data for later. We can actually create and write a new file with the following syntax.

with open('new_file.txt','w') as nf:
    nf.write(str(l))

Now we can check what is in this file.

with open('new_file.txt','r') as nf:
    print(nf.read())
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

It might be best not to have the square brackets present.

with open('new_file.txt','w') as nf:
    for j in l:
        nf.write(str(j)+',')
        
with open('new_file.txt','r') as nf:
    print(nf.read())
0,1,4,9,16,25,36,49,64,81,100,

It is important to note here that when we use the 'w' string when opening a file that already exists we will completely rewrite that file. If we simply want to add to this file we can append using 'a' and if we only want to create a file we can use 'a'.