简体   繁体   English

如何使用python打开文件进行读写? Ubuntu服务器

[英]How do I open a file using python to read and write? Ubuntu server

What I want to do is edit the etc/samba/smb.conf and I want to add 我想做的是编辑etc / samba / smb.conf,然后添加

[Test's Files]
 comment = Test's Files
 path = /files/test
 browsable = yes
 read only = no
 valid users = test

all of this via a Python web application that recieves information from the user's input. 所有这些都是通过Python网络应用程序完成的,该应用程序从用户输入中接收信息。 For now I just want to know how I would add that piece of text to the file with python. 现在,我只想知道如何使用python将那段文本添加到文件中。

You can use the open() function in python to obtain a file: 您可以在python中使用open()函数来获取文件:

with open('path/to/file', 'w') as output_file:
   output_file.write('content')

The second parameter to the open command is the mode. open命令的第二个参数是mode。 More details can be found on the Python documentation website . 可以在Python文档网站上找到更多详细信息。 Side note: if this is in /etc/, then your application may need special permissions to be able to write to this file. 旁注:如果在/ etc /中,则您的应用程序可能需要特殊权限才能写入此文件。 To limit the potential danger of elevated privileges, you should create a subprocess with the elevated permissions that does nothing but write this file so that your main process has normal permissions. 为了限制特权提升的潜在危险,您应该使用提升的权限创建一个子进程,该子进程除了写此文件外什么也不做,以便您的主进程具有正常的权限。

You can look into SMBCOnnection module in python. 您可以在python中查看SMBCOnnection模块。 http://pythonhosted.org/pysmb/api/smb_SMBConnection.html http://pythonhosted.org/pysmb/api/smb_SMBConnection.html

I have already worked with it is a great module to work with smb server. 我已经使用过它,这是一个与smb服务器一起工作的好模块。

with open('path to file', 'w') as fileobj: fileobj.write('text to be written') 使用open('file的路径','w')作为fileobj:fileobj.write('要写入的文本')

the above peice of code is very hand to open, write.And close a file implicitly performing opening and closing operations 上面的代码非常容易打开,编写和关闭文件,隐式地执行打开和关闭操作

You can do that in this simple way: 您可以通过以下简单方式进行操作:

with open('/etc/whatever.txt', 'a+') as file:
    file.write("""[Test's Files]
comment = Test's Files
path = /files/test
browsable = yes
read only = no
valid users = test""")

But you need to pay attention to the permissions if you want to edit files that only root can write. 但是,如果要编辑仅root用户可以写入的文件,则需要注意权限。 Please, pay attention to the mode how you open the file! 请注意你如何打开文件的模式 This must be 'a+' and NOT 'w' as it is shown in other answers! 如其他答案所示,它必须“ a +”不是 “ w”! Otherwise you will overwrite the file! 否则,您将覆盖文件!

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

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