简体   繁体   English

如何在python中组合字符串和字符串变量

[英]How do you combine strings and string variables in python

I'm trying to open a text file with a dynamic path. 我正在尝试使用动态路径打开文本文件。 How could I make it work something like this?: 我如何使它像这样工作?:

f = open("date/month/week.txt","a")

date, month, and week are the current date, month, and week. 日期,月份和星期是当前日期,月份和星期。

You can use str.format : 您可以使用str.format

f = open("{}/{}/{}.txt".format(date, month, week),"a")

I suggest you finish the Python tutorial before trying anything too ambitious! 我建议您在尝试任何野心太大的事情之前先完成Python教程

you can try this. 你可以试试看 using string format and datetime for a complete solution 使用字符串格式和日期时间以获得完整的解决方案

d = datetime.datetime.today()
date = d.date()
month = d.month
week = d.isocalendar()[1]

f = open('{date}/{month}/{week}.txt'.format(date=date, month=month, week=week),"a")

my personal preference on the naming convention for dates and a file would be in the format 'yyyy-mm-dd' you can include the week on this too, which would look like this 我个人对日期和文件的命名约定的偏好为'yyyy-mm-dd'格式,您也可以在其中包含星期,看起来像这样

d = datetime.datetime.today()
date = d.date()
week = d.isocalendar()[1]

f = open('{date}-{week}.txt'.format(date=date, week=week),"a")

that would result in a file of this format. 这将导致这种格式的文件。 2015-06-08-24.txt

Use the datetime module with strftime formatting . datetime模块与strftime格式化一起使用

import datetime
f = open(datetime.datetime.strftime(datetime.datetime.now(), '%d/%m/%U') + '.txt', 'a')

For a date of June 8, 2015, this creates a filename of 08/06/23.txt . 对于2015年6月8日,这将创建文件名08/06/23.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM