简体   繁体   English

无法遍历文件中的单词并将字符串附加到每一行

[英]Can't iterate through words in a file and append string to each line

I am reading in a list of words from a file. 我正在读取文件中的单词列表。 I want to append a string to each word, then print out the word with the appended string. 我想将一个字符串附加到每个单词,然后打印出带有附加字符串的单词。 However, my current code appends the string on a new line. 但是,我当前的代码将字符串附加在新行上。

with open("wordDict.txt") as wordFile:
    for line in wordFile:
        line = line + 'a'
        print(line)

An example output I get is this: 我得到的示例输出是这样的:

hello
a

Output I want to get: 我想要得到的输出:

helloa

Any help appreciated 任何帮助表示赞赏

with open("wordDict.txt") as wordFile:
    for line in wordFile:
        line = line.strip() + 'a'
        print(line)

You need to get rid of the line break at the end of the line. 您需要摆脱行尾的换行符。 .strip() gets rid of whitespace at either end of the line. .strip()在该行的任一行都去除了空格。

with open("wordDict.txt") as wordFile:
    for line in wordFile:
        line = line.rstrip() + 'a'
        print(line)

should do the trick. 应该可以。 rstrip removes trailing whitespace, including newlines. rstrip删除尾随空格,包括换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM