Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用python编写和读取单个文件_Python_File - Fatal编程技术网

如何用python编写和读取单个文件

如何用python编写和读取单个文件,python,file,Python,File,我的项目是使用python从单个txt文件中写入和读取不同的变量 myFile = open("Mygame.txt","w") skill = str(skill) strength=str\n(strength) myFile.write(skill) myFile.write(strength) myFile.close() 我尝试过使用\n,但这似乎不适用于仅打印语句的变量。尝试类似的方法 import shutil with open('test') as old, open('ne

我的项目是使用python从单个txt文件中写入和读取不同的变量

myFile = open("Mygame.txt","w")
skill = str(skill)
strength=str\n(strength)
myFile.write(skill)
myFile.write(strength)
myFile.close()

我尝试过使用\n,但这似乎不适用于仅打印语句的变量。

尝试类似的方法

import shutil
with open('test') as old, open('newtest', 'w') as new:
    for line in old:
        if line.rsplit('|', 1)[-1].strip() == 'number3':
            new.write('this is replacement|number7\n')
        else:
            new.write(line)
shutil.move('newtest', 'test')

将所有统计信息或您正在保存的任何信息放入列表中,然后尝试:

lines = [skill, strength]
myFile.writelines(lines).
已更新
这个答案基于这样一个假设,即您想使用“\n”字符将文本拆分成行。

目前,我对您的问题感到困惑。是否可以添加更多详细信息和/或代码?用于变量读写。是否可以共享一些您编写的代码,以帮助我们了解您的问题所在?您正在读取的文件是什么样子的?什么意思
\n
不适用于变量?你想一行一行地读吗?如果是,请使用
readline
。您可以在中找到有关如何解析文件的更多信息。我需要在一个文本文件中的不同行上写入user1 strength、user1skill、user2strength和user2skill,然后我必须读取每一行。然后将这些数字作为强度和技能变量。这与问题无关,是吗?我在帖子中添加了一个简单版本的编写代码,希望helps@spark它在python中称为列表。