Python: Difference between revisions

From David's Wiki
No edit summary
Line 1: Line 1:
__FORCETOC__
__FORCETOC__


=Installation=
==Installation==
Use [http://anaconda.com Anaconda].
Use [http://anaconda.com Anaconda].


=Basic Usage=
==Basic Usage==
===Lambda Function===
===Lambda Function===
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
Line 10: Line 10:
</syntaxhighlight>
</syntaxhighlight>


==Filesystem Read and Write==
===Filesystem Read and Write===
===List all files in a folder===
====List all files in a folder====
[https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory Reference]
[https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory Reference]
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
Line 21: Line 21:
</syntaxhighlight>
</syntaxhighlight>


===Read entire text file into a list===
====Read entire text file into a list====
[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">
Line 28: Line 28:
</syntaxhighlight>
</syntaxhighlight>


==Regular Expressions (Regex)==
===Regular Expressions (Regex)===
[https://docs.python.org/3/howto/regex.html Reference]<br>
[https://docs.python.org/3/howto/regex.html Reference]<br>
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
Line 38: Line 38:
</syntaxhighlight>
</syntaxhighlight>


=Libraries=
===Spawning Processes===
==Numpy==
Use [https://docs.python.org/3/library/subprocess.html subprocess] to spawn other programs.
<syntaxhighlight lang="python">
import subprocess
subprocess.run(["ls", "-l"])
</syntaxhighlight>
 
==Libraries==
===Numpy===

Revision as of 12:58, 7 October 2019


Installation

Use Anaconda.

Basic Usage

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 entire text file into a list

[1]

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

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

Libraries

Numpy