I want to replace text in a text file with names that are in a csv file. For example, I have a text file that says:
Dear [name here],
Hello . . .. etc etc
And a csv file that has a 2 columns with the first name in the first and the last name in the second:
Joe Smith
Rachel Cool
How would I be able to read in the CSV file, and replace each name with the text [name here] in the file? I have this so far after opening the text and csv file and putting the first and last names in the variable names:
for row in f.readlines():
names = row.split(",")[0], row.split(",")[1]
And after that I tried doing something like this, but it isnt working:
for row in textfile.readlines():
print row.replace("[name here]", names)
And after running it, a TypeError: expected a string or other character buffer error. Assuming because the variable names isnt defined in the second for loop.
But how would I be able to read both files and replace just the [name here] in the text file?
From this line,
names = row.split(",")[0], row.split(",")[1]
names
is a tuple of two string. But then, in this line
row.replace("[name here]", names)
you're trying to use it as a single string.
If you want to write both first/family names, you can append them as suggested in another answer, but why split them in the first place ? You may just read them in the first loop without splitting (which also solves cases where the person a three names (like Herbert George Wells)):
names = row
in the first loop, then
row.replace("[name here]", names)
in the second loop.
If you split the names because you want to use them separately, then it is unclear to me what you want to achieve.
The hint here is in the traceback:
TypeError: expected a string or other character buffer error
replace
expects a string or something that acts like a string. You're feeding it a tuple. Generally, when asking a question here, it is good practice to copy the full traceback so that we know where the error occurs exactly.
Now, you're going to face another issue: in the loop, you erase names
at each iteration.
You should use a list to store all names:
i = 0
for row in f.readlines():
names[i] = row
i += 1
i = 0
for row in textfile.readlines():
print(row.replace("[name here]", names[i]))
i += 1
(Or maybe you did this correctly in your code but you stripped it away when generating a simplified example for your question.)
The replace()
method is expecting a string for the second parameter and you've passed it an array, hence the TypeError.
You can take the two names in the names
array and append them together with a space in the middle using the join
method. Try this:
print row.replace("[name here]", ' '.join(names))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.