Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 421d6d3

Browse files
coool
1 parent 43dd69c commit 421d6d3

File tree

1 file changed

+102
-2
lines changed

1 file changed

+102
-2
lines changed

‎scripting.md‎

Lines changed: 102 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,109 @@ datetime.datetime.fromtimestamp(os.path.getmtime("f.txt"))
7272
| `os.rmdir("someDir")` | Remove directory (provided it's empty) |
7373
| `os.listdir("someDir")` | List files, directories in a directory (argument is optional if you wanna list) |
7474
| `os.path.isdir("someFile")` | Tells you if a path is a dir |
75-
| `os.path.join(dir, name)` | join some string (file name) with a directory path
76-
_intelligently_, so it's portable across OSs |
75+
| `os.path.join(dir, name)` | join some string (file name) with a directory path _intelligently_, so it's portable across OSs |
7776

77+
### Handling CSV Files:
78+
- You'd open and close a CSV file the way you'd do it with any other type of file.
79+
- We need to **`import csv`** to be able to parse a CSV file with **`csv.reader("openedFile")`** as in:
80+
```py
81+
import csv
82+
83+
with open("file.csv") as csvFile:
84+
reader = csv.reader(csvFile)
85+
for row in reader:
86+
print(row)
87+
```
88+
- Each row is a list of elements.
89+
- To generate a csv file, you'd use **`csv.writer("fileTobeWritten").writerows(rows)`** for generating multiple rows. You'd use **`writerow`** instead of `writerows` to generate a single row:
90+
```py
91+
import csv
92+
93+
rows = [["Mobile", "AL"], ["Charleston", "WV"], ["Riverside", "NJ"]]
94+
95+
with open("cities.csv", "w") as file:
96+
writer = csv.writer(file)
97+
writer.writerows(rows)
98+
```
99+
- With **`csv.DictReader(file)`** and **`csv.DictWriter(file)`** you can read and write csv files using dictionaries. Just make sure that such csv files are labeled, meaning the top row has field names.
100+
101+
```py
102+
import csv
103+
records = [{"city": "Mobile", "state": "AL"}, {"city": "Charleston", "state": "WV"}, {"city": "Riverside", "state": "NJ"}]
104+
105+
keys = ["city", "state"]
106+
107+
with open("cities.csv", "w") as cities:
108+
writer = csv.DictWriter(cities, fieldnames = keys)
109+
writer.writeheader()
110+
writer.writerows(records)
111+
```
78112

113+
## Regex:
114+
- Regular expressions in Python can be handled with **`re`** module which include the following great functions:
115+
- **`re.search(pattern, stringToBeMatched)`**: returns a match object. Search whole string for the pattern.
116+
- **`re.match(pattern, stringToBeMatched)`**: returns a match object. Only matches if the string starts with the pattern.
117+
- **`re.findall(pattern, stringToBeMatched)`**: "return all non-overlapping matches of pattern in string, as a list of strings or tupl"
118+
- The first input to these functions need to be a raw string preceded by an **`**`r`**`** as in **`re.match(r"ca", "california")`**. The reason is to prevent confusion when escaping regex special characters, because strings also have escape characters such as `\n`.
119+
- The case can be ignored by adding a third argument as in:
120+
- **`re.match(r"ca", "California", re.IGNORECASE)`**
121+
122+
### Capturing Groups:
123+
- When you surround something in a pattern with parentheses you are capturing a group. The match object your rejex match returns has a function **`groups`** which is a tuple containing these groups. The following example shows how this works:
124+
```py
125+
import re
126+
127+
result = re.match(r"^(\w+), (\w+)$", "Doe, John")
128+
print(result.groups()) # prints ('Doe', 'John')
129+
```
130+
- Indexes on the match object give us access to each of these groups. Conttinuing witht the example abov:
131+
- `result[0]` refers to the whole matched pattern `Doe, John`
132+
- `result[1]` refers to the matched pattern `Doe`
133+
- `result[2]` refers to the matched pattern `John`
134+
- Using groups, we can shuffle the pattern and change it around.
135+
136+
### Splitting:
137+
- **`re.split(pattern, stringToBeMatched)`** splits text using a regex. It spits out a list of split elements. If you you wrap separator(s) in parentheses, everything will be included in the output, including the separators as in:
138+
```py
139+
import re
140+
141+
result = re.split(r"([? ])", "What are you?Nothing")
142+
print(result) # ['What', ' ', 'are', ' ', 'you', '?', 'Nothing']
143+
```
144+
145+
### Replacements:
146+
- Replacements are done with the **`sub`** functions which works as follows:
147+
```py
148+
import re
149+
150+
result = re.sub(r"\d{3}-\d{3}-\d{4}", "[PHONE NUMBER]", "101-101-2020 called at 22:50")
151+
# returns '[PHONE NUMBER] called at 22:50'
152+
```
153+
- This function returned the targeted string but with specified pattern replaced by the substitution pattern.
154+
- `sub` also works like the (in)famous `sed`. You can use it along group capturing tot shuffle hings around as in:
155+
```py
156+
import re
157+
158+
result = re.sub(r"^(\w+), (\w+)$", r"2円 1円", "White, Walter")
159+
```
160+
161+
## Managing Data and Processes:
162+
- This section is about interacting with the OS user and the live interactivity with the OS and processes while they are running!!
163+
- One great interaction tool is the **`input`** function which accept user input in the terminal. It "prompts" the user to input arguments to the program. One stupid example that illustrate the idiomatic usage of this function is as follows:
164+
```py
165+
#!/usr/bin/env python3
166+
167+
print("Welcome to our amazing adder!")
168+
169+
cont = "y"
170+
while cont == "y":
171+
a = b = ""
172+
a = input("Enter first num: ")
173+
b = input("Enter second num: ")
174+
print(int(a) + int(b))
175+
cont = input("Do you wanna perform another operation? [y to continue] ")
176+
print("Good bye!")
177+
```
178+
- The most important thing about the example above is the variable `cont` and how it's used in a loop.
79179

80180

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /