Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/xd-deng/common-questions-in-python
A collection of common questions about Python I encountered, and corresponding solutions
https://github.com/xd-deng/common-questions-in-python
Last synced: 22 days ago
JSON representation
A collection of common questions about Python I encountered, and corresponding solutions
- Host: GitHub
- URL: https://github.com/xd-deng/common-questions-in-python
- Owner: XD-DENG
- Created: 2015-10-09T09:13:54.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2015-10-09T14:19:21.000Z (over 9 years ago)
- Last Synced: 2024-10-31T06:07:06.741Z (2 months ago)
- Size: 133 KB
- Stars: 3
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## Common-Questions-in--Python
A collection of common questions about Python I encountered, and corresponding solutions### 1. How to get the current time in Python?
```
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2015, 10, 9, 17, 15, 30, 498779)
>>> test = datetime.datetime.now()
>>> test.date()
datetime.date(2015, 10, 9)
>>> test.time()
datetime.time(17, 15, 38, 72927)
```### 2. How to get current directory and change the directory?
```
>>> import os
>>> os.getcwd()
'/Users/nus/Documents'
>>> os.chdir("/Users/nus")
>>> os.getcwd()
'/Users/nus'
```### 3. How to get the current user name?
```
>>> import pwd
>>> import os
>>> pwd.getpwuid(os.getuid())
pwd.struct_passwd(pw_name='nus', pw_passwd='********', pw_uid=501, pw_gid=20, pw_gecos='NUS', pw_dir='/Users/nus', pw_shell='/bin/bash')
>>> pwd.getpwuid(os.getuid())[5]
'/Users/nus'
>>> pwd.getpwuid(os.getuid())[0]
'nus'
``````
>>> from getpass import getuser
>>> getuser()
'nus'
```### 4. How to get the path of the current script?
```
# Please note this only works for script, and does NOT work interactively.
import os
print os.path.realpath(__file__)
```### 5. How to get the unique values (distinct values) in a list?
```
>>> test = [1,2,3,2,1,4,5,4]
>>> test
[1, 2, 3, 2, 1, 4, 5, 4]>>> set(test)
set([1, 2, 3, 4, 5])
>>> list(set(test))
[1, 2, 3, 4, 5]
``````
>>> test = ["a", "b", "a", "c"]
>>> list(set(test))
['a', 'c', 'b']
```