简体   繁体   English

使用 Python 以大写形式保存文本文件

[英]save text file in upper case using Python

I'm trying to make the program that convert all words to uppercase.我正在尝试制作将所有单词转换为大写的程序。

a = open("file.txt",encoding='UTF-8')

for b in a:
    c = b.rstrip()
    print(c.upper())
a.close()

this is my code it prints uppercase text.这是我的代码,它打印大写文本。 But it can't save the file on 'file.txt'.但它无法将文件保存在“file.txt”上。 I want to convert all words to uppercase.我想将所有单词转换为大写。

How can I solve it????我该如何解决????

Here's how you can do it: [provided that you are working with a small file]您可以这样做: [前提是您使用的是小文件]

Open the file in read mode store the uppercase text in a variable;read mode打开文件将大写文本存储在变量中; then, open another file handler in write mode and write the content into it.然后,以write mode打开另一个文件处理程序并将内容写入其中。

with open('file.txt' , 'r') as input:
    y = input.read().upper()
with open('file.txt', 'w') as out:
    out.write(y)

First convert the txt into the string:首先将txt转成字符串:

with open('file.txt', 'r') as file:
    data = file.read()

And then revise the data to the uppercase:然后将数据修改为大写:

data_revise = data.upper()

Finally revise the texts in the file:最后修改文件中的文本:

fout = open('data/try.txt', 'w')
fout.write(data_revise)

You can actually do this "in place" by reading and writing a character at a time.实际上,您可以通过一次读取和写入一个字符来“就地”执行此操作。

with open("file.txt", "r") as f:
    while (b := f.read(1)) != '':
        f.write(b.upper())

This is safe because you are processing the file one byte at a time (and writing one byte for every byte read) and not using seek to potentially overwrite a byte before it is read.这是安全的,因为您一次处理一个字节(并为读取的每个字节写入一个字节),而不是使用seek在读取之前可能覆盖一个字节。 The file-like object's underlying buffering and your system's disk cache means this isn't as inefficient as it looks.类文件对象的底层缓冲和系统的磁盘缓存意味着这并不像看起来那么低效。

(This does make one assumption: that the encoded length of b is always the same as b.upper() . I suspect that should always be true. If not, you should be able to read and write at least a line at a time, though not in place: (这确实做出了一个假设: b的编码长度始终与b.upper()相同。我怀疑这应该总是正确的。如果不是,您应该能够一次至少读写一行,虽然没有到位:

with open("input.txt") as inh, open("output.txt", "w") as outh:
    for line in inh:
        print(line.upper(), file=outh)

) )

You can write all changes to temporary file and replace original after all data processed.您可以将所有更改写入临时文件并在处理完所有数据后替换原始文件。 You can use either map() or generator expression :您可以使用map()生成器表达式

with open(r"C:\original.txt") as inp_f, open(r"C:\temp.txt", "w+") as out_f:
    out_f.writelines(map(str.upper, inp_f))
with open(r"C:\original.txt") as inp_f, open(r"C:\temp.txt", "w+") as out_f:
    out_f.writelines(s.upper() for s in inp_f)

To replace original file you can useshutil.move() :要替换原始文件,您可以使用shutil.move()

import shutil
...
shutil.move(r"C:\temp.txt", r"C:\original.txt")

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

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