码迷,mamicode.com
首页 > 编程语言 > 详细

「Python」- 代码片段 @20210123

时间:2021-01-25 11:18:58      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:文件   dog   cat   arch   整理   date   str   修改   tps   

作为一个Python菜鸡,有些常用的代码和方法还是要整理一下的:

#!python3

################################################################################################################################################################
# 多行代码可以使用反斜线,一种经典的做法
################################################################################################################################################################

################################################################################################################################################################
# 打印字典或者数组什么的
# https://stackoverflow.com/questions/15785719/how-to-print-a-dictionary-line-by-line-in-python
################################################################################################################################################################
print(json.dumps(dicObject, indent = 4, ensure_ascii=False)) # 并显示UNICODE字符,而不时是转义序列

################################################################################################################################################################
# Python String endswith() Method
# https://www.tutorialspoint.com/python/string_endswith
################################################################################################################################################################
str.startswith(suffix[, start[, end]])
str.endswith(suffix[, start[, end]])

################################################################################################################################################################
# TypeError: ‘<‘ not supported between instances of ‘dict‘ and ‘dict‘
# https://stackoverflow.com/questions/55695479/typeerror-not-supported-between-instances-of-dict-and-dict
################################################################################################################################################################
dic.sort(key=lambda x: x[0][‘name‘], reverse=False)

################################################################################################################################################################
# Python3 格式化输出 %s & %d 等 / python - heredoc or multiline string
# https://www.cnblogs.com/alfred0311/p/7735539.html
# http://lofic.github.io/tips/python-heredoc.html
################################################################################################################################################################
print ("Name:%-10s Age:%08d Height:%08.2f" % ("Alfred", 25, 1.70))
"{name} was {place}".format(name=‘Louis‘, place=‘here‘)

################################################################################################################################################################
# 如何在 Python3 中定义和使用常量
# https://blog.csdn.net/jieming2002/article/details/78379264
# TODO 需要定义一个类
################################################################################################################################################################

################################################################################################################################################################
# Python here document without newlines at top and bottom
# https://stackoverflow.com/questions/9589301/python-here-document-without-newlines-at-top-and-bottom
################################################################################################################################################################
print ‘‘‘
dog
cat
‘‘‘[1:-1]

print ‘‘‘
dog
cat
‘‘‘.strip()

################################################################################
# How to get the date N days ago in Python
# https://www.saltycrane.com/blog/2010/10/how-get-date-n-days-ago-python/
################################################################################
from datetime import datetime, timedelta
date_N_days_ago = datetime.now() - timedelta(days=N)

################################################################################################################################################################
# Python之三目运算符
# https://www.cnblogs.com/wanghao123/p/7921654.html
################################################################################################################################################################
a = x if (x>y) else y

################################################################################################################################################################
# What‘s the correct way to convert bytes to a hex string in Python 3?
# https://stackoverflow.com/questions/6624453/whats-the-correct-way-to-convert-bytes-to-a-hex-string-in-python-3
################################################################################################################################################################
b‘\xde\xad\xbe\xef‘.hex()
bytes.fromhex(‘deadbeef‘)

################################################################################################################################################################
# Iterate over a dictionary in Python
# https://www.geeksforgeeks.org/iterate-over-a-dictionary-in-python/
################################################################################################################################################################
for state in statesAndCapitals: 
    print(state)
  
################################################################################################################################################################  
# Check if a given key already exists in a dictionary
# https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary
################################################################################################################################################################
# in is the intended way to test for the existence of a key in a dict.

################################################################################################################################################################
# Accessing the index in ‘for‘ loops?
# https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops
################################################################################################################################################################
for idx, val in enumerate(ints):
    print(idx, val)

# 文件操作

################################################################################################################################################################
# Read only the first line of a file?
# https://stackoverflow.com/questions/1904394/read-only-the-first-line-of-a-file
################################################################################################################################################################
infile = open(‘filename.txt‘, ‘r‘)
firstLine = infile.readline()

################################################################################################################################################################
# Prepend line to beginning of a file
# https://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file
################################################################################################################################################################
def line_prepender(filename, line):
    with open(filename, ‘r+‘) as f:
        content = f.read()
        f.seek(0, 0)
        f.write(line.rstrip(‘\r\n‘) + ‘\n‘ + content)

################################################################################################################################################################
# Python Recipe: Open a file, read it, print matching lines
# https://palewi.re/posts/2008/04/05/python-recipe-open-a-file-read-through-it-print-each-line-matching-a-search-term/
################################################################################################################################################################
for line in open("wssnt10.txt", "r"):
    if re.match("(.*)(L|l)ove(.*)", line):
        print line,

################################################################################################################################################################
# How do I specify new lines on Python, when writing on files?
# https://stackoverflow.com/questions/11497376/how-do-i-specify-new-lines-on-python-when-writing-on-files
# 换行符可以使用「os.linesep」,但是如果是写入文件的话,直接使用「\n」即可,因为Python会自动处理。
################################################################################################################################################################

################################################################################################################################################################
# Directing print output to a .txt file in Python 3
# https://stackoverflow.com/questions/36571560/directing-print-output-to-a-txt-file-in-python-3
################################################################################################################################################################
print("I have a question.", file=open("output.txt", "a"))

################################################################################################################################################################
# 获取文件的修改时间
################################################################################################################################################################
import os
mtime = os.path.getmtime(file_path)

################################################################################################################################################################
# Python os.utime() Method
# https://www.tutorialspoint.com/python/os_utime.htm
################################################################################################################################################################
# Modifying atime and mtime
os.utime("a2.py",(1330712280, 1330712292))

获取当前代码文件路径

How do I get the filepath for a class in Python? - Stack Overflow
python - Get location of the .py source file - Stack Overflow

# 获取类文件路径
import inspect
inspect.getfile(C.__class__)

# 获取 .py 文件路径
import os
os.path.abspath(__file__)

「Python」- 代码片段 @20210123

标签:文件   dog   cat   arch   整理   date   str   修改   tps   

原文地址:https://www.cnblogs.com/k4nz/p/14317429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!