python文件内容显示

时间:2017-11-03 07:48:27

标签: python file

这是一个简单的程序,它打开一个文件,一些内容写在文件中,然后我尝试打印它,但输出不正常。

fo= open("linkinpark.txt", "r+") #file open in red and write mode
print 'Is the file closed?: ',fo.closed
print 'What is the mode of access?: ',fo.mode
print 'Name of the file?: ',fo.name
print 'Softspace flag: ',fo.softspace
fo.write( "I tried so hard and got so far \n but in the end it doesn't even matter\n" ) #content is written in file
res=fo.read(10)
print" The data in file is: ",res #print the content of file stored in res 
fo.close()
print 'Is the file closed?: ',fo.closed()


output what I am getting is:  The data in file is:   or  The data in file is:  n Stack Vi

2 个答案:

答案 0 :(得分:0)

你可以这样做:

test1.txt文件中的原始文本是:test12312 然后使用Python 3.x

file = open('C:/Users/S1626A/Desktop/test1.txt', 'r+')

print('The content of file is: ', file.read(4))

结果:

Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
======== RESTART: C:\dev\Svarbiausi_tekstiniai_failai\sandbox\test.py ========
The content of file is:  test
>>> 

提醒一下,如果您只想在文件中添加一些文字,请不要使用w, r+,因为它会覆盖您文件中的所有内容,而是使用a,这意味着要追加。喜欢

fileToAppend = open('path/file.txt', 'a')
fileToAppend.write('some text')
fileToAppend.read()
fileToAppend.close()

答案 1 :(得分:0)

它的工作我试过这样:

fo= open("linkinpark.txt", "r+") #file open in red and write mode
print('Is the file closed?: ',fo.closed)
print('What is the mode of access?: ',fo.mode)
print('Name of the file?: ',fo.name)
fo.write( "I tried so hard and got so far \n but in the end it doesn't even matter\n" ) #content is written in file
res=fo.read(10)

print(" The data in file is: ",res) #print the content of file stored in res
fo.close()
print('Is the file closed?: ',fo.closed)

输出:

Is the file closed?:  False
What is the mode of access?:  r+
Name of the file?:  linkinpark.txt
 The data in file is:  I tried so
Is the file closed?:  True
  在我的案例中,

文件"linkinpark.txt"在程序启动时为空。

     

我对您的代码有一些建议:

当您使用' open'时,请使用'with open'代替'open'。你不用担心关闭文件,它会自动关闭。

您可以这样做:

with open("linkinpark.txt",'r+') as fo:
    fo.write("I tried so hard and got so far \n but in the end it doesn't even matter\n")  # content is written in file