在python里建一个文件夹里面一行有一个索引号根据索引号查找文件一行的内容
时间: 2023-09-09 11:05:51 浏览: 118
你可以使用以下代码在Python中创建一个文件夹,并将每行内容与索引号存储到文件中:
```python
import os
def create_folder(folder_name):
if not os.path.exists(folder_name):
os.makedirs(folder_name)
print(f"The folder '{folder_name}' has been created.")
else:
print(f"The folder '{folder_name}' already exists.")
def write_file(folder_name, data):
file_path = os.path.join(folder_name, "data.txt")
with open(file_path, "w") as file:
for index, line in enumerate(data, start=1):
file.write(f"{index}: {line}\n")
print(f"The file '{file_path}' has been created.")
# 创建文件夹
folder_name = "my_folder"
create_folder(folder_name)
# 写入文件
data = [
"This is line 1.",
"This is line 2.",
"This is line 3."
]
write_file(folder_name, data)
```
这将创建一个名为 "my_folder" 的文件夹,并在其中创建一个名为 "data.txt" 的文件。每行内容都会带有索引号,如下所示:
```
1: This is line 1.
2: This is line 2.
3: This is line 3.
```
要根据索引号查找文件中的一行内容,您可以使用以下代码:
```python
def read_line(folder_name, index):
file_path = os.path.join(folder_name, "data.txt")
with open(file_path, "r") as file:
lines = file.readlines()
if 1 <= index <= len(lines):
line = lines[index-1].strip()
return line
else:
return "Invalid index."
# 从文件中读取指定索引号的一行内容
line_index = 2
line_content = read_line(folder_name, line_index)
print(f"Line {line_index}: {line_content}")
```
这将输出:
```
Line 2: This is line 2.
```
请确保提供正确的索引号,以避免出现"Invalid index."的错误消息。
阅读全文
相关推荐
















