问题是我正在尝试编写代码,以便将我的.txt文件重新写入其自身更易于管理的版本中。该“程序”需要一次读取七行,然后将其作为一行写到另一个.txt文件中,然后重复此功能,直到遍历整个.txt文件为止。
我一直在Internet上查找并尝试过多种方法,但是以下代码甚至都无法与我所需要的最接近。
first_line = 7
def function():
with open ('file_txt', 'r') as read_file1:
line = [next(read_file1) for x in range(first_line)]
with open ('file_txt_new', 'w') as write_file2:
write_file2.write(str(line))
输入文本文件如下:
Awakened Shrub
Small plant, unaligned
Hit Points:
10 (3d6) Armor Class:
9 Speed:
20 ft. Challenge Rating:
0 (10 XP)
预期结果:这些结果只是原始文本文件在一行中被重写。
示例1:这将写在新文本文档的第一行上。
Awakened Shrub, Small plant, unaligned, Hit Points: 10 (3d6) Armour Class: 9
示例2:这将写在新文本文档的第二行。
Baboon, Small beast, unaligned, Hit Points: 1 (1d4 - 1) Armour Class: 9
实际结果:
['Awakened Shrub\n', 'Small plant, unaligned\n', 'baboon\n', 'Small beast, unaligned\n',]
答案 0 :(得分:1)
您的代码正在制作list
,但是要执行您想要的操作,您需要将它们放回一个字符串中(str(line)
不会这样做,因为那样会产生字符串list
的表示形式;您需要str.join
):
first_line = 7
def function():
# Open output file once up front (or you'll replace it for each new set of seven lines)
with open('file_txt', 'r') as read_file1, open('file_txt_new', 'w') as write_file2:
while True:
# Get the lines, providing a default value to next in case you run out of lines
lines = [next(read_file1, '') for x in range(first_line)]
# Convert to a single string, and replace newlines with `, ` matching expected output
newline = ''.join(lines).rstrip('\n').replace('\n', ', ')
# Got nothing but empty lines, must have exhausted file, so we're done
if not newline:
break
write_file2.write(newline + "\n")
注意:您可以使用itertools.islice
来稍微简化/加快代码的速度,前提是允许导入模块,请替换:
lines = [next(read_file1, '') for x in range(first_line)]
具有:
lines = itertools.islice(read_file1, first_line)
答案 1 :(得分:0)
我认为以下代码可以帮助您:
if(response.data.is_success){
mainView.router.loadPage({url:'user-product.html', ignoreCache:true,
reload:true });
}
到达文件末尾时,将引发num_reads = 7
with open('data.txt') as read_file:
with open('new_data.txt', 'w') as write_file:
while (True):
lines = []
try: # You should expect errors if the number of lines in the file are not a multiplication of num_reads
for i in range(num_reads):
lines.append(next(read_file)) # when the file finishes an exception occurs here
#do sutff with the lines (exactly num_reads number of lines)
processed = " ".join(list(map(lambda x: x.replace("\n", ''), lines)))
write_file.write(processed + '\n')
except StopIteration: # here we process the (possibly) insufficent last lines
#do stuff with the lines (less that num_reads)
processed = " ".join(list(map(lambda x: x.replace("\n", ''), lines)))
write_file.write(processed + '\n')
break
错误并被StopIteration
捕获,您可以在其中处理捕获到的可能不足的数据行并跳出except
循环。在上面的代码中,我对完全捕获(num_reads = 7)和部分捕获都执行了相同的操作。处理部分仅附加行并删除换行符。
当while
像这样时:
data.txt
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
会像这样:
new_data.txt