简体   繁体   English

打印.txt文件Python

[英]Printing a .txt File Python

I need some help Im trying to display the text files contents (foobar) with this code 我需要一些帮助,我试图用此代码显示文本文件的内容(foobar)

 text = open('C:\\Users\\Imran\\Desktop\\text.txt',"a")
    rgb = text.write("foobar\n")
    print (rgb)
    text.close()

for some reason it keeps displaying a number. 由于某种原因,它一直显示数字。 If anyone could help that would be awesome, thanks in advance 如果有人可以帮助您,那将非常好,谢谢

EDIT: I am Working with Python 3.3. 编辑:我正在使用Python 3.3。

Print the contents of the file like this: 像这样打印文件的内容:

with open(filename) as f:
    for line in f:
        print(line)

Use with to ensure that the file handle will be closed when you are finished with it. 使用with可以确保完成文件句柄后将其关闭。

Append to the file like this: 像这样附加到文件:

with open(filename, 'a') as f:
    f.write('some text')

If you want to display the contents of the file open it in read mode f=open("PATH_TO_FILE", 'r') 如果要显示文件的内容,请以读取模式打开它f=open("PATH_TO_FILE", 'r')

And then print the contents of file using 然后使用以下命令打印文件内容

for line in f:
    print(line)     # In Python3.

And yes, don't forget to close the file pointer f.close() after you finish the reading 是的,不要忘记在完成读取后关闭文件指针f.close()

You are printing the number of written bytes. 您正在打印写入的字节数。 That won't work. 那行不通。 Also you might need to open the file as RW. 另外,您可能需要以RW格式打开文件。

Code: 码:

text = open('...', "a")
text.write("foo\n")
text = open('...', "r")
print text.read()
# Open a file
fo = open("foo.txt", "r+")
str = fo.read();
print "Read String is : ", str
# Close opend file
fo.close()

More: http://www.tutorialspoint.com/python/python_files_io.htm 更多: http : //www.tutorialspoint.com/python/python_files_io.htm

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

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