从文件中读取特定数据边读边写入另一个文件
时间: 2024-05-06 10:19:03 浏览: 17
可以使用Python中的文件操作来实现。下面是一个简单的示例代码:
```python
# 打开原始文件和目标文件
with open('source.txt', 'r') as source_file, open('target.txt', 'w') as target_file:
# 逐行读取原始文件
for line in source_file:
# 如果该行包含特定数据,则写入目标文件
if '特定数据' in line:
target_file.write(line)
```
在上述代码中,我们使用了Python中的`with open`语法来打开原始文件和目标文件。`source.txt`是我们要读取的原始文件,`target.txt`是我们要写入的目标文件。
接下来,我们使用`for`循环逐行读取原始文件。我们可以在每一行中查找特定数据,如果该行包含特定数据,则将其写入目标文件中。
最后,我们使用`with open`语法中的`with`块,在完成所有读写操作后自动关闭文件,以确保数据正确地写入目标文件中。
相关问题
从文件中读取特定行数据边读边写入另一个文件的最后一行
可以使用Python的文件读写操作来实现这个功能:
```python
with open('input.txt', 'r') as input_file, open('output.txt', 'a') as output_file:
# 读取特定行数据
for line_number, line in enumerate(input_file):
if line_number == 2: # 读取第三行数据
# 写入到输出文件的末尾
output_file.write(line)
```
在这个例子中,我们打开了两个文件,一个是输入文件 `input.txt`,另一个是输出文件 `output.txt`。我们使用 `enumerate()` 函数来遍历输入文件的每一行,同时记录当前行号。当行号为 2 时(即第三行),我们将该行数据写入到输出文件的末尾。这里使用了输出文件的追加模式 `'a'`,使得新的数据不会覆盖原来的数据。
需要注意的是,在使用完文件后,应该使用 `with` 语句来关闭文件,以释放文件资源。
c语言从一个文件读取到链表在写入另一个文件
下面是一个示例代码,可以从一个文件中读取数据到链表中,然后将链表中的数据写入到另一个文件中:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
typedef struct Node {
int data;
struct Node *next;
} Node;
// 从文件中读取数据到链表中
Node* readFromFile(char* filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error opening file %s\n", filename);
return NULL;
}
Node *head = NULL;
Node *tail = NULL;
int data;
while (fscanf(fp, "%d", &data) != EOF) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
fclose(fp);
return head;
}
// 将链表中的数据写入到文件中
void writeToFile(char* filename, Node *head) {
FILE *fp = fopen(filename, "w");
if (fp == NULL) {
printf("Error opening file %s\n", filename);
return;
}
Node *p = head;
while (p != NULL) {
fprintf(fp, "%d ", p->data);
p = p->next;
}
fclose(fp);
}
int main() {
Node *head = readFromFile("input.txt"); // 从 input.txt 文件中读取数据到链表中
writeToFile("output.txt", head); // 将链表中的数据写入到 output.txt 文件中
return 0;
}
```
在这个示例代码中,readFromFile() 函数从指定的文件中读取数据到链表中,writeToFile() 函数将链表中的数据写入到指定的文件中。在 main() 函数中,我们先调用 readFromFile() 函数将数据读取到链表中,然后再调用 writeToFile() 函数将链表中的数据写入到文件中。
需要注意的是,在使用完链表后,需要手动释放链表中的内存,以避免内存泄漏。可以使用如下的代码来释放链表中的内存:
```c
void freeList(Node *head) {
Node *p = head;
while (p != NULL) {
Node *tmp = p;
p = p->next;
free(tmp);
}
}
```
这个函数会遍历链表,释放每个节点的内存。在 main() 函数中,我们可以在程序结束前调用 freeList() 函数来释放链表中的内存:
```c
int main() {
Node *head = readFromFile("input.txt"); // 从 input.txt 文件中读取数据到链表中
writeToFile("output.txt", head); // 将链表中的数据写入到 output.txt 文件中
freeList(head); // 释放链表中的内存
return 0;
}
```