创建中间步骤温度变量是否重要?python中字符串的动态内存分配是如何完成的



上传到看门狗文件夹的文件示例名称:300_processtest_20201008_092912_rx.csv

我从看门狗处理程序获得如下文件路径:

elif event.event_type == 'created':
temp = {}
print ("Received created event - %s." % event.src_path)
file = event.src_path
req_id, d_type = get_requestID(file)
temp['requestID'] = "req_id"
temp['data_type'] = d_type
with open(file) as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter='|')
temp['data'] = list(csv_reader)
r = requests.post(url = UPDATE_ENDPOINT, json = json.loads(json.dumps(temp))) 

def get_requestID(file_path):
split_string = file_path.rpartition("/")
file_name = split_string[2]
remove_extension = file_name.rpartition(".")
split_name = split_extension[0].rsplit("_",2)
data_type = split_name[2]
request_id = split_name[1]
print(request_id, data_type)
# Does doing above thing in one line, saves memory usage?
#split_name = file_path.rpartition("/")[2].rpartition(".")[0].rpartition("_",2)
#data_type = split_name[2]
#request_id = split_name[1]
return request_id, data_type 

我想知道哪种方式写代码更好。我不确定python中的内存分配是如何工作的,特别是这里提到的字符串(字符串内部(。如果这是真的

使用临时变量的方法1占用了更多的内存,但可读性很强。

方法2把它写在一行里有点难以阅读和理解。


最初我认为两种方法都需要相同的内存,即创建临时变量不需要额外的内存是吗这让我怀疑我从来没有真正关注过python是如何工作的。

利用pathlib模块-

from pathlib import Path
def get_requestID(file_path):
file_path =  Path(file_path)
file_name = file_path.name
split_extension = file_path.suffix
request_id1 = split_extension[0].rpartition("_")
request_id2 = file_path.rpartition("/")[2].rpartition(".")[0].rpartition("_")
return request_id2[2] 

最新更新