用Python创建一个文件,并且文件命名规则是Wenjian+获取当前时间至年月日时分秒
时间: 2024-04-11 22:27:23 浏览: 15
下面是使用Python创建一个文件,并按照指定的命名规则命名的示例代码:
```python
import datetime
# 获取当前时间
current_time = datetime.datetime.now()
# 定义文件名
file_name = "Wenjian" + current_time.strftime("%Y%m%d%H%M%S") + ".txt"
# 创建文件
with open(file_name, "w") as file:
# 在文件中写入内容
file.write("This is a test file.")
print("文件创建成功,文件名为:", file_name)
```
以上代码中使用了`datetime`模块来获取当前时间,并使用`strftime`方法将时间格式化为指定的格式。然后将格式化后的时间与固定部分的文件名拼接起来,最终得到完整的文件名。使用`open`函数创建文件,并使用`with`语句来自动关闭文件。在文件中写入内容后,输出创建成功的提示信息,同时打印出文件的完整路径和文件名。
请注意,以上代码是一个示例,你可以根据自己的需求进行修改和扩展。同时,确保在执行文件操作时具有足够的权限。
相关问题
用python求文件wenjian.txt中行最长字符串的长度以及行最短字符串长度,并打印出来。
可以使用Python中的文件操作和字符串处理函数来实现这个任务。代码如下:
```python
with open('wenjian.txt', 'r') as file:
lines = file.readlines() # 读取所有行
longest_len = 0
shortest_len = float('inf') # 初始化为一个很大的数,确保能找到更短的行
for line in lines:
line_len = len(line.strip()) # 去除行末换行符并计算长度
if line_len > longest_len:
longest_len = line_len
if line_len < shortest_len:
shortest_len = line_len
print("最长行长度:", longest_len)
print("最短行长度:", shortest_len)
```
解释一下代码:
首先使用`with open('wenjian.txt', 'r') as file`打开文件,并使用`readlines()`方法读取所有行,返回一个字符串列表。
然后遍历所有行,使用`strip()`方法去除行末的换行符,再使用`len()`方法计算行的长度。如果当前行的长度比已知的最长长度长,则更新最长长度;同理,如果当前行的长度比已知的最短长度短,则更新最短长度。
最后打印出结果即可。
用python从键盘输入 10个字符串,至少有两个字符串中含有“the”, 每个字符串不超过100个字符,建立一个文本文件wenjian.txt,每个字符串占一-行。
可以使用以下代码实现:
```python
# 输入10个字符串
strings = []
count = 0
while count < 10:
s = input(f"请输入第{count+1}个字符串:")
if "the" in s:
strings.append(s)
count += 1
else:
print("该字符串不含有'the',请重新输入。")
# 将字符串写入文件
with open("wenjian.txt", "w") as f:
for s in strings:
f.write(s + "\n")
```
首先通过一个循环,从键盘输入10个字符串,并将包含“the”的字符串添加到列表中。如果某个字符串不含有“the”,则会提示重新输入。
接着,使用`with open()`语句打开文件并将每个字符串写入文件中,每个字符串占一行。最后,文件会保存在当前工作目录下的`wenjian.txt`文件中。