如何在python中连接两个文本文件

2024-04-28 08:18:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文本文件 ['i', 'hate', 'sausages', 'noa', 'hate', 'i']

然后是一个数字文件

1,2,3,3,2,1

现在我需要试着把这两个文件连接起来

这就是我目前所拥有的

positionlist=open('positions.txt', 'r')#opening the code files with the postions

wordlist=open('Words.txt', 'r')#opening the word files 

positions = positionslist.read() #the code is reading the file to see what it is in the txt and is saving them as a vairable    
words = wordslist.read() #the code is reading the file to see what it is in the txt and is  saving them as a vairable  

print(positions) #prints the positions
print(words)     #prints the words 
positionfinal = list(positions) # makes the postions into a list

#this is where i need to tey and connect the two codes together 

remover = words.replace("[","") #replacing the brackes withnothing so that it is red like a string
remover = remover.replace("]","")#replacing the brackes withnothing so that it is red like a string 

Tags: and文件thetotxtiscodeit
1条回答
网友
1楼 · 发布于 2024-04-28 08:18:47

输入文件的格式看起来像Python文本(字符串列表、整数元组),因此可以使用^{}来解析它。然后可以使用内置的^{}函数将它们循环在一起并打印出来。像这样:

import ast

with open('words.txt') as f:
    words = ast.literal_eval(f.read())  # read as list of strings

with open('positions.txt') as f:
    positions = ast.literal_eval(f.read())  # read as tuple of ints

for position, word in zip(positions, words):
    print(position, word)

输出如下:

1 i
2 hate
3 sausages
3 noa
2 hate
1 i

相关问题 更多 >