Python: Difference between revisions

From David's Wiki
No edit summary
Line 29: Line 29:
</syntaxhighlight>
</syntaxhighlight>


====Read entire text file into a list====
====Read/Write entire text file into a list====
Reading <br>
[https://stackoverflow.com/questions/3925614/how-do-you-read-a-file-into-a-list-in-python/3925701]
[https://stackoverflow.com/questions/3925614/how-do-you-read-a-file-into-a-list-in-python/3925701]
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
with open('C:/path/numbers.txt') as f:
with open('C:/path/numbers.txt') as f:
     lines = f.read().splitlines()
     lines = f.read().splitlines()
</syntaxhighlight>
Writing<br>
[https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python/899176]
<syntaxhighlight lang="python">
with open('your_file.txt', 'w') as f:
    f.write("\n".join(my_list))
</syntaxhighlight>
</syntaxhighlight>



Revision as of 12:12, 10 October 2019


Installation

Use Anaconda.

Basic Usage

How to use Python 3.

Ternary Operator

Reference

is_nice = True
state = "nice" if is_nice else "not nice"

Lambda Function

lambda x: x * 2

Filesystem Read and Write

List all files in a folder

Reference

gazeDir = "Gaze_txt_files"
# List of folders in root folder
gazeFolders = [path.join(gazeDir, x) for x in os.listdir(gazeDir)]
# List of files 2 folders down
gazeFiles = [path.join(x, y) for x in gazeFolders for y in os.listdir(x)]

Read/Write entire text file into a list

Reading
[1]

with open('C:/path/numbers.txt') as f:
    lines = f.read().splitlines()

Writing
[2]

with open('your_file.txt', 'w') as f:
    f.write("\n".join(my_list))

Regular Expressions (Regex)

Reference

import re
myReg = re.compile(r'height:(\d+)cm')
myMatch = re.match(myReg, "height:33cm");
print(myMatch[1])
# 33

Spawning Processes

Use subprocess to spawn other programs.

import subprocess
subprocess.run(["ls", "-l"], cwd="/")

Libraries

Numpy