简体   繁体   中英

how to make add , , to every word in an .txt file with python

I have a long.txt file with a lot of words in it. That kinda looks like this

bosstones 
boston 
both 
bottom 
bowie 
bowl 

but i want to add this, at the end and the start of every line. That would look like this

,bosstones, 
,boston, 
 ,both, 
,bottom, 
,bowie, 
,bowl, 

So can i do that in python?

Consider you have a file named a.txt which has all the words, you can create a new file using the following script.

f = open('a.txt', 'r+')
data = f.read()
f.close()
g = open('new_a.txt', 'w+')
for d in data.splitlines():
    g.write(f',{d.strip()},\n')
g.close()
with open("yourTextFile.txt", "r") as f: data = f.read().split("\n") with open("yourOutput.txt", "w") as f: newdata = '' for line in data: newdata += ","+line+",\n" f.write(newdata)line in data:

There's a few different concepts we'll need to cover here.

Reading from a file

To read from a file, first you need to open it. Python gives us good tools to manage this. The first is open , which lets you open the file for reading.

open is a function that takes two parameters. The first is the name of the file. The second is the "mode" that you want to open it in. We want to read from the file, so we can use 'r' .

input_file = open('input.txt', 'r')

To manage the file, you can open it in a context using with . This sounds complicated, but it actually makes things much easier.

with open('input.txt', 'r') as input_file:
    # Inside this block, we can do whatever we need to do with input_file

Now to read the data from the file, there are several functions you can use, but readlines probably makes the most sense. The readlines function returns an iterable (a list) that contains all the lines in your file. So you can read all the text in your file and print it out like so:

with open('input.txt', 'r') as input_file:
    for line in input_file.readlines():
        print(line)

Modifying strings

The next thing you'll need to be able to do is modify a string. For your case, the best way to do that is to use f-string , which let you format new strings. It can be a bit difficult to explain, so I'll give an example.

test1 = 'hello'
test2 = f'+{test1}+'
print(test2)  # Prints '+hello+'

In an f-string , anything enclosed in curly braces ( '{}' ) is read as a variable and inserted into the string. Very helpful!

Something else you'll need to watch out for is newline characters . When you read in a line from the file, the line includes a newline character ( '\n' ). You'll want to remove this. If you don't, here's what happens.

test1 = 'hello\n'
test2 = f'+{test1}+'
print(test2)
# Prints
# +hello
# +

The '\n' character actually gets printed and creates a new line in the output. No good, Luckily: there is a function to automatically remove any leading or trailing newline characters: strip . We can fix the above example:

test1 = 'hello\n'
test1 = test1.strip()
test2 = f'+{test1}+'
print(test2)
# Prints
# +hello+

Writing to a file

Lastly, we'll need to write the modified string out to a file. You still need to open the file with open , but instead you should specify 'w' as the second parameter for 'write'. You can still use a context manager just like before. To write to the file, you just need to use the write function. The file doesn't even need to exist, if it doesn't, Python will automatically create it.

with open('output.txt', 'w') as output_file:
    output_file.write('Hello world!\n')
    output_file.write('You can write multiple lines!\n')

Note that we need to add the newline characters back in when we write to the output.

Putting it all together

You can put this all together a number of ways, but I'd probably do it like this.

with open('input.txt', 'r') as input_file:
    with open('output.txt', 'w') as output_file:
        for line in input_file.readlines():
            line = line.strip()
            line = f',{line},\n'
            output_file.write(line);

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