简体   繁体   中英

Python: How to capitalize the first column of a .txt file.

I have a .csv formatted .txt file. I am deliberating over the best manner in which to .capitalize the text in the first column.

.capitalize() is a string method, so I considered the following; I would need to open the file, convert the data to a list of strings, capitalize the the required word and finally write the data back to file.

To achieve this, I did the following:

newGuestList = []
with open("guestList.txt","r+") as guestFile :
guestList = csv.reader(guestFile)
for guest in guestList :
    for guestInfo in guest :
        capitalisedName = guestInfo.capitalize()
        newGuestList.append(capitalisedName)

Which gives the output:
['Peter', '35', ' spain', 'Caroline', '37', 'france', 'Claire','32', ' sweden']

The problem:

Firstly; in order to write this new list back to file, I will need to convert it to a string. I can achieve this using the .join method. However, how can I introduce a newline, \\n , after every third word (the country) so that each guest has their own line in the text file?

Secondly; this method, of nested for loops etc. seems highly convoluted, is there a cleaner way?

My .txt file: peter, 35, spain\\n caroline, 37, france\\n claire, 32, sweden\\n

You don't need to split the lines, since the first caracter of the first word is the first caracter of the line :

with open("lst.txt","r") as guestFile :
    lines=guestFile.readlines()
    newlines=[line.capitalize() for line in lines]
with open("lst.txt","w") as guestFile :
    guestFile.writelines(newlines)   

You can just use a CSV reader and writer and access the element you want to capitalize from the list.

import csv
import os

inp = open('a.txt', 'r')
out = open('b.txt', 'w')

reader = csv.reader(inp)
writer = csv.writer(out)

for row in reader:
    row[0] = row[0].capitalize()
    writer.writerow(row)

inp.close()
out.close()

os.rename('b.txt', 'a.txt') # if you want to keep the same name

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.

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