我刚刚开始学习Python,我遇到了一个问题,如果程序关闭,我想保存一个整数以便再次使用。我一直在环顾四周,但找不到任何相关信息。我到目前为止编写的代码:
from __future__ import print_function
collatz = open("collatz.txt", "w+")
Num = 5
calcNum = Num
while Num>0:
if calcNum % 2 == 0:
calcNum /= 2
print(calcNum, file = collatz)
else:
calcNum = (calcNum*3)+1
print(calcNum, file = collatz)
if calcNum == 4:
print("The infinite loop has been reached, moving on to the next number.", file = collatz)
Num += 1
print(Num, file = collatz)
calcNum = Num
我尝试将Num
保存到另一个文件中,然后使用它来保存它。但是,它会保存为字符串而不是int
,因此我尝试使用int()
但仍然没有帮助。
提前感谢您的帮助。
答案 0 :(得分:3)
使用泡菜库。
// ...
import Collapse from '@material-ui/core/Collapse';
// ...
class NestedList extends React.Component {
state = { open: true };
handleClick = () => {
this.setState({ open: !this.state.open });
};
render() {
const { classes } = this.props;
return (
<div className={classes.root}>
<List
component="nav"
subheader={<ListSubheader component="div">Nested List Items</ListSubheader>}
>
{/* ... */}
<ListItem button onClick={this.handleClick}>
<ListItemIcon>
<InboxIcon />
</ListItemIcon>
<ListItemText inset primary="Inbox" />
{this.state.open ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={this.state.open} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
<ListItem button className={classes.nested}>
<ListItemIcon>
<StarBorder />
</ListItemIcon>
<ListItemText inset primary="Starred" />
</ListItem>
</List>
</Collapse>
</List>
</div>
);
}
}
答案 1 :(得分:0)
你可以使用JSON然后如果它的Python或其他语言读入并运行你的部分结果(不限于int)并不重要。这是一个程序的例子,它(无效地)计算了一些素数,并在每次运行时从中断的地方开始:
import json
from math import factorial
from os.path import isfile
FILE_NAME = "number.json"
def is_prime(x): # not efficient, but short (by @aikramer2)
return factorial(x - 1) % x == x - 1
if isfile(FILE_NAME):
with open(FILE_NAME) as handle:
number = json.load(handle)
else:
number = 2 # no seed, begin anew
print(number)
for number in range(number + 1, number + 10):
if is_prime(number):
print(number)
with open(FILE_NAME, "w") as handle:
json.dump(number, handle)