我使用以下代码在一行上插入文字:
exp = 82
with open ('test.txt','r') as b:
lines = b.readlines()
with open('test.txt','w') as b:
for i,line in enumarate(lines):
if i == exp:
f.write('test_data')
f.write(line)
这将在第82行插入文本。如何修改它以便它可以在第82行第一次运行时插入文本,然后在下次运行时插入第83行,然后第84行等等。我在考虑使用一个柜台,但我不确定。
答案 0 :(得分:1)
这样做的方法是增加一个计数器。
counter = exp
stop = 90
with open('test.txt', 'w') as b:
for i, line in enumerate(lines):
if i == counter and i != stop:
b.write('test_data')
b.write(line)
else:
break
counter += 1
答案 1 :(得分:0)
您可以使用文本文件存储代码已运行的次数。从文本文件中读取此值并将其添加到ex。然后递增代码运行次数的值并将其写入文本文件,然后运行您编写的代码。
#include <SD.h>
#include <SPI.h>
int linenumber = 0;
const int buffer_size = 54;
int bufferposition;
File printFile;
char character;
char Buffer[buffer_size];
boolean SDfound;
void setup()
{
Serial.begin(9600);
bufferposition = 0;
}
void loop()
{
if (SDfound == 0)
{
if (!SD.begin(53))
{
Serial.print("The SD card cannot be found");
while(1);
}
}
SDfound = 1;
printFile = SD.open("Part1.txt");
if (!printFile)
{
Serial.print("The text file cannot be opened");
while(1);
}
while (printFile.available() > 0)
{
character = printFile.read();
if (bufferposition < buffer_size - 1)
{
Buffer[bufferposition++] = character;
if ((character == '\n'))
{
//new line function recognises a new line and moves on
Buffer[bufferposition] = 0;
//do some action here
bufferposition = 0;
}
}
}
Serial.println(Buffer);
delay(1000);
}
答案 2 :(得分:0)
如果您不想完全循环浏览文件,可以使用以下内容:
#!/usr/bin/python
exp = 5
seq = ["This is new line\n","This is new line\n"]
# Open a file
fo = open("foo.txt", "r+b")
lngth = 0
#count the number of char until the desired line
for i in range(1,exp):
line = fo.readline()
lngth = len(line) + lngth
# read the rest of the file
lines = fo.read()
# go back to insert position
fo.seek(lngth, 0)
# insert sequence in file
fo.writelines(seq)
# write rest of the file
fo.write(lines)
# Close opend file
fo.close()
对于原始测试输入:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
This is 6st line
This is 7nd line
This is 8rd line
This is 9th line
This is 10th line
我有以下内容:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is new line
This is new line
This is 5th line
This is 6st line
This is 7nd line
This is 8rd line
This is 9th line
This is 10th line
如果你有一个巨大的文件,你无法负担加载到RAM(参见fo.read),你可能想要使用枚举和逐行处理的其他一些解决方案。 希望这有帮助!